ShopDev Labs RSS Feed Feb 6

Text Resizing With jQuery

XHTML & CSS, 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).


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:

  1. Size in ‘pixels’
  2. Sixe in ‘points’
  3. Size in ‘em’
  4. 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; }); });

Why not take a look at this simple demonstration page.

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.







<a href=index.php?i=1&m=1&u=http%3A%2F%2Fwww.shopdev.co.uk%2Fblog%2Ftext-resizing-with-jquery%2F%22http%3A%2F%2Fwww.mysite.com%2F%22%3Esome site</a> <blockquote>quote</blockquote> <em>some emphasized text</em> <strong>some bold text</strong> <pre lang="">some code</pre> To add code to your comments, simply wrap the code inside <pre> tags. Syntax highlighting will be added if you define the language. Example:
<pre lang="php">some code</pre>
Supported "lang" attribute values: html4strict, css, php, javascript, xml & mysql
Copyright © 2008, ShopDev
Mobilize:
images: on /off
Save this page at PhoneFavs.

Original version.
Mobilized by PhoneFavs