Sunday, January 15, 2012

Text Resizing With jQuery

Ever wondered how to allow visitors to increase or decrease the text size (font size) on your website? I’m going to show you how - using jQuery (a great JavaScript library).


View Demo

CSS Font Size

Firstly, we should consider the various methods of specifying a font size using CSS. 4 CSS attributes pertaining to font sizing come to mind:

Size in ‘pixels’
Sixe in ‘points’
Size in ‘em’
Size as a percentage - ‘%’
For the purpose of this article, treat ‘em’ and ‘%’ as the same (where 1em is equivalent to 100%). When we allow visitors to change the font size, only elements with a font size set in ‘em’ or as a percentage will be variable. Elements without this attribute fall back to the value of their immediate parent element’s font-size. This means is that if you specify the value for an element’s font size in pixels, the font size will not change.

The JavaScript



$(document).ready(function(){
  // Reset Font Size
  var originalFontSize = $('html').css('font-size');
    $(".resetFont").click(function(){
    $('html').css('font-size', originalFontSize);
  });
  // Increase Font Size
  $(".increaseFont").click(function(){
    var currentFontSize = $('html').css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    var newFontSize = currentFontSizeNum*1.2;
    $('html').css('font-size', newFontSize);
    return false;
  });
  // Decrease Font Size
  $(".decreaseFont").click(function(){
    var currentFontSize = $('html').css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    var newFontSize = currentFontSizeNum*0.8;
    $('html').css('font-size', newFontSize);
    return false;
  });
});


One limitation of this short script is that the visitor’s preference is not saved. We could overcome this limitation by storing the font-size to a cookie.  Jonny and Fazal have cooked up some nice code that will do just this.  View the comment.

No comments:

Post a Comment