Building a reusabe font size controller interface using jQuery

January 14, 2009 by admin · 10 Comments
Filed under: jQuery, Tutorials 

Most of the web2.0 design allows the user to change the font size of the main content area. This is indeed a good usability. So I thought, I should contribute something here. The result is a small jQuery code which can be used to generate a font size changer interface.

Only thing you need to make is a holder element for the controller and then call the function like

fontSize("#holder", "#content", 9, 12, 20);
// holder is the id of the element where the font size controller interface will be shown
// content is the id of the element where the font size changes will take place.
// The next three arguments are Minimum font size, Default font size and Maximum font size respectively

Yes, all done and it will automatically generate all required buttons. It also supports jquery cookie plugin. So when you open the page again, the preferred font size will be restored automatically. (Cookie plugin is not required, but recommended)

After the function is called, the controllers will be generated in the specified area like the following.

Advantages

  • Small size, built on jQuery
  • Fully skinnable using css
  • Multiple interface can be used in the same page for two different content areas
  • Support jQuery Cookie plugin for remembering the preferred font size
  • Very easy to use

The logic

  • The function will be called with the holder element and target element with default, maximum and minimum font size
  • Create three elements for decreasing, default and increasing font size
  • Style the elements using CSS so that it will be fully skinnable
  • Upon clicking read the current font size for the target and calculate the new font size. Then apply it to target element
  • Save the modified font size value to cookie, so that the preferred font size can be saved and restored

The CSS

We need some buttons for the backgrounds and the best places to search is Icon look, Icon Finder and Icon Let as usual. I found the above images, but you can use another or design yours.

Now we need to style the elements. Mainly we need 5 styles – Button for smaller font, default font and larger font. We need two more styles for the disabled state of buttons. (If current font size is the minimum or maximum allowed, we need to show a disabled state).

 
 
.smallFont {
	outline: none; /*for making it look nice in FF */
	background: url(images/font-down.png);
	text-indent: -9999px;
	display: block;
	float: left;
	width: 32px;
	height: 32px;
}
 
.defaultFont {
	/*if you want to hide the default font button, use display:none */
	background: url(images/font-default.png);
	text-indent: -9999px;
	outline: none;
	display: block;
	float: left;
	width: 32px;
	height: 32px;
}
 
.largeFont {
	background: url(images/font-up.png);
	outline: none;
	text-indent: -9999px;
	display: block;
	float: left;
	width: 32px;
	height: 32px;
}
 
.ldisabled,.sdisabled { /*Styles for disabled buttons*/
	opacity: 0.3;
	-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";
	/*This is for IE8 */
	filter: alpha(opacity = 30);
}

As you can see I’ve used three background images for the three buttons. Need to set the display:block property as the buttons are of 32px height. I could have optimized the css more by applying common styles to elements. For eg: For the three styles only background is different, so it could’ve declared like the following.

 .smallFont, .defaultFont, .largeFont { 
.... /*common properties*/
}
 
.smallFont { background: url(...) } 
...

But I didn’t use that because it will be easier to declare as is now, if you want to use different sized images or different styles for each button.

If you want to have multiple styles in the same page, just use the CSS scope

For eg:

 #container1 .smallFont { ... }
#container2 .smallFont { ... }

Now for the disabled state I used same style for all buttons. Using opacity filter is the easiest way to imitate a disabled button. Here for IE8, I have used an extra style after googling around.

The jQuery function

I didn’t write it as a jQuery plugin because I didn’t find it useful to have the chainable functionality.

function fontSize(container, target, minSize, defSize, maxSize) {
	/*Editable settings*/
	var minCaption = "Make font size smaller"; //title for smallFont button
	var defCaption = "Make font size default"; //title for defaultFont button
	var maxCaption = "Make font size larger"; //title for largefont button
 
 
	//Now we'll add the font size changer interface in container
	smallFontHtml = "<a href='javascript:void(0);' class='smallFont' title='" + minCaption +"'>" + minCaption + "</a> ";
	defFontHtml = "<a href='javascript:void(0);' class='defaultFont' title='" + defCaption +"'>" + defCaption + "</a> ";
	largeFontHtml = "<a href='javascript:void(0);' class='largeFont' title='" + maxCaption +"'>" + maxCaption + "</a> ";
	$(container).html(smallFontHtml + defFontHtml + largeFontHtml);
 
	//Read cookie &amp; sets the fontsize
	if ($.cookie != undefined) {
		var cookie = target.replace(/[#. ]/g,'');
		var value = $.cookie(cookie);
		if (value !=null) {
			$(target).css('font-size', parseInt(value));
		}
	}
 
	//on clicking small font button, font size is decreased by 1px
	$(container + " .smallFont").click(function(){ 
		curSize = parseInt($(target).css("font-size"));
		newSize = curSize - 1;
		if (newSize >= minSize) {
			$(target).css('font-size', newSize);
		} 
		if (newSize <= minSize) {
			$(container + " .smallFont").addClass("sdisabled");
		}
		if (newSize < maxSize) {
			$(container + " .largeFont").removeClass("ldisabled");
		}
		updatefontCookie(target, newSize); //sets the cookie 
 
	});
 
	//on clicking default font size button, font size is reset
	$(container + " .defaultFont").click(function(){
		$(target).css('font-size', defSize);
		$(container + " .smallFont").removeClass("sdisabled");
		$(container + " .largeFont").removeClass("ldisabled");
		updatefontCookie(target, defSize);
	});
 
	//on clicking large font size button, font size is incremented by 1 to the maximum limit
	$(container + " .largeFont").click(function(){
		curSize = parseInt($(target).css("font-size"));
		newSize = curSize + 1;
		if (newSize <= maxSize) {
			$(target).css('font-size', newSize);
		} 
		if (newSize > minSize) {
			$(container + " .smallFont").removeClass("sdisabled");
		}
		if (newSize >= maxSize) {
			$(container + " .largeFont").addClass("ldisabled");
		}
		updatefontCookie(target, newSize);
	});
 
	function updatefontCookie(target, size) { //Private function for setting cookie
		if ($.cookie != undefined) { //If cookie plugin available, set a cookie
			var cookie = target.replace(/[#. ]/g,'');
			$.cookie(cookie, size);
		} 
	}
}

I think the code is self explanatory. If you’ve any doubt in code, please feel free to ask here :)

Usage

Include the css file, then after including jQuery include this script like the following (Don’t forget to change the path as required. Also, you need to copy the images in correct folder as specified in CSS file or edit the CSS file to make it correct.

<link rel="stylesheet" type="text/css" href="font-controller.css" />
<script src="jquery-1.2.6.pack.js"></script> 
<script src="font-controller.js"></script>
<script src="jquery.cookie.js"></script>

The function can be called inside a $document.ready() as usual. For eg:

fontSize("#container", "#content", 9, 12, 20);

Then inside your html create the empty container for holding the elements. Give it an ID or class, if possible ID.

<div id="container"></div> ... 
<div id="content">... Font size of this element can be controlled.... </div>

Do not copy paste the code from this page. Instead download the full demo from below link

Demo

View Demo | Download full demo

Please feel free to post your comments and suggestions for improvement :)

Related posts:

  1. Vertical alignment of contents inside an element using jQuery
  2. Add icons to your links automatically using jQuery & CSS
  3. jQuery seekAttention plugin to get the users attention
  4. Make curved corners with jQuery Corner plugin
  5. How to make your forms better with jQuery?

If you like this post, please share it so that others can also find this

Comments

10 Responses to “Building a reusabe font size controller interface using jQuery”
  1. Goran Juri? says:

    Nice one.

    Just one small bug to fix. Clicking on the “default size” button does not reset the cookie value.

  2. admin says:

    Oops! That was a copy paste problem :) .

    Thank you very much for pointing it out.

    Fixed it now. Please download the new files and try (demo is also updated).

  3. rtpHarry says:

    This has issues in IE6.

    On first load if you click + it goes greyed out. If you then click minus it goes to massive text. If you click reset it works fine (either after the text has exploded or first thing)

    I am intending on modifying the code to see if I can call reset when the set loads.

  4. rtpHarry says:

    Yes this fixed it. Add this in at line 70 (right after you setup the click function for defaultFont:

    // rtpHarry – call default click to fix IE6 resize bug
    $(container + ” .defaultFont”).click();

  5. admin says:

    Thanks for checking this in IE6 and suggesting this method to fix the issue. But this overrides the cookie settings and thus cookie becomes useless.

    But can you please check again in IE6 after clearing all cache files? (http://demos.cool-javascripts.com/jquery-fontsize-controller.html) Because I couldn’t find this problem in my test machine. I think the following lines of code handles the situation. ( I have added those lines some days earlier).

    //Read cookie & sets the fontsize
    if ($.cookie != undefined) {
    var cookie = target.replace(/[#. ]/g,”);
    var value = $.cookie(cookie);
    if (value != null) {
    $(target).css(‘font-size’, parseInt(value));
    } else {
    $(target).css(‘font-size’, defSize);
    }
    }

    //If cookie is not set, the default font size applied to make sure IE takes it as pixels rather than em or %

    Please check http://demos.cool-javascripts.com/jquery-fontsize-controller.html

  6. rtpHarry says:

    Hey, I was just testing the site and I realised that this was preventing the cookie from working so I changed the code around and came back to post it. Looks like we created virtually the same code. Will use yours seeing as you are the one that knows the code inside out!

    Mine was:
    //Read cookie & sets the fontsize
    if ($.cookie != undefined) {
    var cookie = target.replace(/[#. ]/g,”);
    var value = $.cookie(cookie);
    if (value !=null) {
    $(target).css(‘font-size’, parseInt(value));
    }
    // call default click to fix IE6 bug
    else {
    $(container + ” .defaultFont”).click();
    }
    }

  7. rtpHarry says:

    (also I just noticed that you havent updated the jQuery code in the article to reflect this fix)

  8. rtpHarry says:

    You still haven’t updated the article to include the fix we discussed… tut tut! :)

  9. wh says:

    cool script
    is it possible to set font-size with relative measurements like em, %
    otherwise it will not harmonize with wcag 2.0 1.4.4 rezize text

  10. Yokhannan says:

    Hello,

    When I implement this, I would like the cookie to remember the setting for every page where I call this at. For me, that is not working. If it should be, I guess I messed up. If not, could somebody please explain to me the process to get it work, thanks!

    Yokhannan

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!