« Back to the blog

A very simple font resizer

This demo uses JQuery to implement a very simple font resizing widget. There are only 2 options for the font size — small and large — thereby keeping the UI very clean. I've implemented 'current state highlighting' to make it clearer. Try it out using the font resize links at the top of this page.

The script also uses the JQuery Cookie Plugin to make the font size selection persistent across pages. You can visit another page to see that your font size choice is carried over. Note that you need to include the Cookie Plugin separately from the main JQuery library.

Get the code

To get the full code, just look at the source for this page. But here's the main Javascript bit:

$(document).ready(function() {
		
	     // declare a few constants:
	     var SMALL = 14; //small font size in pixels
	     var LARGE = 16; //larger size in pixels
	     var COOKIE_NAME = "Simple-Fontresizer"; //Maybe give this the name of your site.

	     //make it small by default
	     var fontsize = SMALL; 

	     // Only show text resizing links if JS is enabled
	     $(".fontresize").show();

	     // if cookie exists set font size to saved value, otherwise create cookie
	     if($.cookie(COOKIE_NAME)) {
		     fontsize = $.cookie(COOKIE_NAME);
		     //set initial font size for this page view:
		     $("body").css("font-size", fontsize + "px");
		     //set up appropriate class on font resize link:
		     if(fontsize == SMALL) { $("#small").addClass("current"); }
		     else { $("#large").addClass("current"); }
	     } else {
		     $("#small").addClass("current");
		     $.cookie(COOKIE_NAME, fontsize);
	     }

	     // large font-size link:
	     $("#large").bind("click", function() {
			     if(fontsize == SMALL) {
			     fontsize = LARGE;
			     $("body").css("font-size", fontsize + "px");
			     $("#large").toggleClass("current");
			     $("#small").toggleClass("current");
			     $.cookie(COOKIE_NAME, fontsize);
			     }
			     return false;	
			     });
	     
	     // small font-size link:
	     $("#small").bind("click", function() {
			     if(fontsize == LARGE) {
			     fontsize = SMALL;
			     $("body").css("font-size", fontsize + "px");
			     $("#large").toggleClass("current");
			     $("#small").toggleClass("current");
			     $.cookie(COOKIE_NAME, fontsize);
			     }
			     return false;	
			     });
});