Sign up for our newsletter

Email Address:

We endorse and use:

We use Code Spaces for our SVN Repository
We use nopCommerce for our open source e-commerce solutions
We use Umbraco for our open source CMS solutions
We use SilverStripe for our open source CMS solutions
We use SourceForge for our open source project hosting
We use the 960.gs css grid for our projects

Valid CSS!

Valid HTML 4.01 Transitional

Code snippets: A really easy javascript accessibility text size selector

Posted by Ed Nice on 14 October 2009 | 1 Comments

Tags: , , , , ,

A client asked me recently about upgrades to a web application. One of the required upgrades was to add text sizing.

If you don't know what this is, it's just putting some options in place to allow the web site visitor to choose which font size they use to view your web site. You can see this example in action over there >>>

Many modern browsers let you do this, but adding the option to your web site alows the visitor easy access to the functionality.

So, we sat down and I discussed the presentation with the designer.

I suggested a little paragraph in the sidebar that said something like:

Text size: a b c.

We decided against the +/- option, as it can get a bit stupid and I think 3 presented sizes are enough.

I thought a little bit more about how to implement this, the requirements being:

Simple
Re-usable
Client side

So, the decision was to offer 3 links, one for each size option, set a cookie to remember the selection next time, and using javascript/css only.

Here's how we did it.

We use some prototype functions to help with events and element manipulation, so you need to get rototype and reference it in your html page.

You can download and read about prototype at http://www.prototypejs.org/

Reference it in your html page like:

   
<script src="prototype.js" type="text/javascript"></script>

So, you can make a test web page, referencing prototype, using the code below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <title>A simple font re-sizer using prototype and js</title>
   <script src="prototype.js" type="text/javascript"></script>
</head>

<body>
<p>Some content?</p>
</body>
</html>

Ok, so far, so good. Next we need to create our own javascript handler file and add some other stuff, such as cookie handling that I don't think prototype does? (but it might. I have never looked).

So, our file will need to have an event listener to check for the page loading. Create a file called something like resize.js. It will look something like:

Event.observe(window, 'load', function()
{
   some-function-call-here();
});

You can also add a reference to this .js file in the html file by adding:

<script src="resize.js" type="text/javascript"></script>

...to the head of the html example.

Next, we need to create a function that sets the font size based on a passed value. So, we add something like:

function setFontSize(size)
{
   // Set the font size here...
}

So how do we change the global font size?

I decided that adding something like 'style="font-size:0.9em;"' in the body or main wrapper tag would work and also let us use some of prototype's great functionality to handle setting the style.

Now we are going to use prototype's $() method to help us, so we need to add something to the setFontSize function, so it uses the size passed in, like:

function setFontSize(size)
{
   var sSize = size+"px";
   $('app').style.fontSize = sSize;
}

This uses pixels, but you could use ems too (this site now uses this example based around ems).

Note we use $('app') to reference something that we set the style of. This is simply a shortcut, provided by prototype, to replace the getElementById() javascript function.

For our example, this means we are applying this style to an element in the dom called 'app', so we need to point it out in the htmlfor prototyp to find by giving something an id="app" attribute.

You can target anything in the html, but the body tag or an outer wrapper div will work best. If, for any reason, your body tag already has an id for something else, just use that in the function call instead of 'app'.

Either way, the body tag in your html should look something like:

<body id="app">

So if we now update the main event handler to call the resizing function, we now have:

Event.observe(window, 'load', function()
{
   setFontSize(12);
});

If you open the .html file in a browser, you should see some text and no errors. You can now see if the javascript we have added works. Simply change the parameter in the function call inside the event listener to something like 25. The text hould be huge. If it is, we know it's ok so far.

Great, that worked first time for me too.

Now we have done that, we have a few issues we need to resolve.

We need to add something to allow a resize to be done manually and also to 'remember' the size change.

Let's do the manual re-size first.

This is really simple.

In the body of the html file, add a paragraph like:

<p>Text: <a href="#" style="font-size:15px;" onclick="setFontSize(15);">15</a></p>

Now save and reload the html file. Click the link, the font size changes. Cool.

You can use your own formatting and presentation, but here is a nice sample, offering 3 size options. Remember, you can use as many as you like in your own apps:

<p>
Text:size: <a href="#" style="font-size:13px;" onclick="setFontSize(13);">13</a> <a href="#" style="font-size:15px;" onclick="setFontSize(15);">15</a> <a href="#" style="font-size:18px;" onclick="setFontSize(18);">18</a>
</p>

Try it out. You get 3 options and it is updated immediately when you select. Excellent.

Ok, but each time we reload the page, it defaults back to the base font size, so we need to use cookies to check for any previous size selection and also to store any subsequent selections.

Here are some javascript cookie handlers. add them to your resize.js file above the current content:

function createCookie(name,value,days)
{
   if (days)
   {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
   }
   else
   {
      var expires = "";
   }
   document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
   var nameEQ = name + "=";
   var ca = document.cookie.split(';');

   for(var i=0;i < ca.length;i++)
   {
      var c = ca;
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0)
      {
         return c.substring(nameEQ.length,c.length);
      }
   }
   return null;
}

function eraseCookie(name)
{
   createCookie(name,"",-1);
}

I'm not going to cover the cookie handling code apart from saying it allows us to check for and set a cookie using javascript.

We now need to do 2 things.

Check for any existing resize cookie and use the value if it's there.
Add or update the cookie when we call the resize function.

We will do the first requirement by checking for a valid cookie in the load event handler.

By adding an if/else statement, we can check for cookies and fall back on the default value if there isn't one. Change your resize.js so that the Event.observe handler looks like:

if (readCookie('resize') == null)
   {
      setFontSize(12);
   }
   else
   {
      var size = readCookie('resize');
      setFontSize(size);
   }

Now we have the ability to check for a cookie and use it, we need to add that little extra bit that sets the cookie for us for next time. Edit the setFontSize() function so it looks like:

function setFontSize(size)
{
   var sSize = size+"px";
   $('app').style.fontSize = sSize;
   createCookie('resize', size, 30);
}

Now reload the page and test it. You should have 3 opions to resize text which are remembered next time a visitor accesses the page

Here are the 2 pages we used in full.

resize.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <title>A simple font re-sizer using prototype and js</title>
   <script src="prototype.js" type="text/javascript"></script>
   <script src="resize.js" type="text/javascript"></script>
</head>

<body id="app">
<p>
Text:size: <a href="#" style="font-size:13px;" onclick="setFontSize(13);">13</a> <a href="#" style="font-size:18px;" onclick="setFontSize(18);">18</a> <a href="#" style="font-size:24px;" onclick="setFontSize(24);">24</a>
</p>
<p>Some content?</p>
</body>
</html>

resize.js

function createCookie(name,value,days)
{
   if (days)
   {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
   }
   else
   {
      var expires = "";
   }
   document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
   var nameEQ = name + "=";
   var ca = document.cookie.split(';');

   for(var i=0;i < ca.length;i++)
   {
      var c = ca;
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0)
      {
         return c.substring(nameEQ.length,c.length);
      }
   }
   return null;
}

function eraseCookie(name)
{
   createCookie(name,"",-1);
}

Event.observe(window, 'load', function()
{
   if (readCookie('resize') == null)
   {
      setFontSize(12);
   }
   else
   {
      var size = readCookie('resize');
      setFontSize(size);
   }
});

function setFontSize(size)
{
   var sSize = size+"px";
   $('app').style.fontSize = sSize;
   createCookie('resize', size, 30);
}

And that's it. Simple text re-sizing in the client using client side javascript which can be used in almost any web site, application and project.

It has been tested and works ok in IE7+ and Firefox but should also be fine in other versions plus Safari/Opera/IceWeasel etc.

Thanks for reading.

/ed.


Post your comment

Comments

  • I noticed that, when using this on a web site, there was a 'jump' as the page loaded, then re-adjusted to the selected text size.

    This was just annoying more than anything else.

    To fix it, simply ensure that you have a base font size defined in your CSS, that matches the smallest text size option.

    You still get a small kick when the site is set to a larger font by the user, but it is less obvious than the page defaulting to 1em or whatever for half a second, then bumping down to 0.8.

    Posted by Ed Nice, 15/10/2009 12:05pm (3 years ago)

RSS feed for comments on this page | RSS feed for all comments

Text size: Aa Bb Cc

Follow us on...

N-WebDesign news

Terms :: Privacy :: © N-Web Design 2012