Resizing font unobtrusive with jQuery and save in cookie
Posted by info on 23rd January 2010
Do you need an unobtrusive font resizing component which also remember the settings in a cookie?
With jQuery i’ve created a little piece of html and javascript. This piece can simply be loaded in your html container by using the jquery function load().
This is an unobtrusive way to add this component to your website and only is available in your source when javascript is enabled. Here is the simple code I used to add the functionality:
$(function() {
//show resize buttons
$('.resizers').load('setFontSizeComponent.html');
});
Inside the inserted piece of html I placed this javascript code block:
//load the font-size cookie if it exists and change body font var currentFontSize = $('html').css('font-size'); var currentFontSizeNum = parseInt(currentFontSize, 10); $.originalFontSize = parseInt($.cookie('fontsize'),10) || currentFontSizeNum; $('html').css('font-size',$.originalFontSize + 'px'); $('.font-label').text('Size: ' + $.originalFontSize); // Reset Font Size $('.bh_resetFont').click(function(event){ event.preventDefault(); fsCResizeText(0); }); // Increase Font Size $('.bh_increaseFont').click(function(event){ // prevent url event.preventDefault(); fsCResizeText(1); }); // Decrease Font Size $(".bh_decreaseFont").click(function(event){ // prevent url event.preventDefault(); fsCResizeText(-1); }); /** * resize html base font size. when 0 value is passed the original fontsize on start of the page is reset * @addition{integer} number to increase the fontsize */ function fsCResizeText(addition) { var newFontSize; if (addition == 0) { // reset size newFontSize = $.originalFontSize; } else { var currentFontSize = $('html').css('font-size'); var currentFontSizeNum = parseInt(currentFontSize, 10); // set fontsize between 8 and 20 px newFontSize = Math.max(8,Math.min(20,currentFontSizeNum+addition)); } $('html').css('font-size', newFontSize); // Create (or update) the value of a cookie: $.cookie('fontsize', newFontSize); $('.font-label').text('Size: ' + newFontSize); }
You need the jquery library and the cooky plugin for jquery
Here you can find the simple example page
http://www.frontendplace.nl/bb/wp-content/uploads/2010/resizer/setpagesize.html
The separate component you can load here
Posted in Scripting | 1 Comment »

