Javascript - text resize with cookie

I was telling you in a previous article - Javascript - text resize - how you can give your site’s visitors the possibility to see your page’s content at different text sizes, using javascript. Let’s take this further and think a little about the user… now, if he really needs a bigger text size, then he will have to use those buttons or links on each page - not so convenient, right?

Well, don’t you worry about this because that’s what we have cookies for! :smile:

Using the same example as in the previous article, here is what you have to do:

1. Add two more functions to the javascript file for cookie’s handling

Javascript code:

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;
}
 
function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

The createCookie function has three parameters: the name and value of the cookie and the number of days it is to remain active. If you set the number of days to 0 the cookie is trashed when the user closes the browser. If you set the days to a negative number the cookie is trashed immediately.
In my example, I used “textsizestyle” as cookie’s name, javascript variable textsize as value and I set it to be active for 365 days: createCookie("textsizestyle", textsize, 365);.


The readCookie function has only one parameter: the name of the cookie. It returns the value of that cookie or null.
In my example, I used “textsizestyle” as cookie’s name: readCookie("textsizestyle");

More info on these two functions and cookies in general here: http://www.quirksmode.org/js/cookies.html.

2. Use createCookie to store user’s preferred text size

I used it in the fsize function, so that each time the user change the text size, the font value is stored in the cookie. Here is the modified fsize function:

function fsize(size,unit,id){
  var vfontsize = document.getElementById(id);
  if(vfontsize){
    vfontsize.style.fontSize = size + unit;
    createCookie("textsizestyle", textsize, 365);
  }
}

 
3. Use readCookie to change text size on rendering

I added the following piece of code at the end of the page to read the cookie’s value and in case there is a value stored into the cookie to force the page content to be render at that specific font size.

<script type="text/javascript">
var cookie = readCookie("textsizestyle");
textsize = cookie ? cookie : 10;
fsize(textsize,'px','content');
</script>

 
 
To make it easy, I have put them all js functions in a javascript file, ready for you to download and add to your site.

Download Javascript Text Resize File

That’s it! Enjoy!

If you found this useful, please consider a small donation!


Thanks!

Tags: , , ,

Popularity: 49% [?]


1 Star2 Stars3 Stars4 Stars5 Stars (13 votes, average: 4 out of 5)
Loading ... Loading ...

Check out this video!!

Write a Comment

Take a moment to comment and tell me what you think. Some basic HTML is allowed for formatting.

*
To prove that you're not a bot, enter this code
Anti-Spam Image

Type your comment here.

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

Reader Comments

Hi Nick, have you been successful in integrating this type of capability into a WordPress blog? Any chance you could give us a demo on your next post?

Before doing that, I searched and I found that there is already such a plugin for wordpress.

I looked over the code and it use cookies too. If it’s not working let me know and I’ll make a plugin out of mine… :)

Hey Nick,

You seem to be a pro at text-size cookies, and I was wondering if you might be able to help me out. I’m using a similar script to yours, except, it is cookieless. Is there any way you might be able to show me how to enable them?

Thanks a lot, I really appreciate your help on this- it’s been driving me bananas :)

Here’s the code:

var tags = new Array( ‘div’,'td’,'tr’,'p’,'b’,'table’,’strong’,'emphasis’,'a’,'h1′,’h2′,’h3′,’pre’,’sub’,’sup’,'i’,'th’,'cp’,'ul’,'ol’,'li’,'dt’,'dd’);
var pixelArray = new Array(’10′,’12′,’16′,’20′,’24′,’30′,’40′);
var emArray = new Array(’0.7′,’0.9′,’1.0′,’1.5′,’2.0′,’2.5′,’3′);
var initSize = 0;

function fontSizer(inc,unit) {
if (!document.getElementById)
return;
var size = initSize;
size += inc;
if (size 6 ) {
size = 6;
}
initSize = size;
getBody = document.getElementsByTagName(’body’)[0];
for (i = 0 ; i

Here is the whole function:

function fontSizer(inc,unit) {
if (!document.getElementById)
return;
var size = initSize;
size += inc;
if (size < 0 ) {
size = 0;
}
if (size > 6 ) {
size = 6;
}
initSize = size;
getBody = document.getElementsByTagName(’body’)[0];
for (i = 0 ; i < tags.length ; i++ ) {
getallTags = getBody.getElementsByTagName(tags[i]);
for (k = 0 ; k < getallTags.length ; k++)
getallTags[k].style.fontSize = (unit==’px’) ? pixelArray[size]+unit : emArray[size]+unit;
}
}

It seems to be fine - could you give me more details about your problem?

Hi Nico,

Thanks for completing my post. The problem with the aforementioned function is that it doesn’t seem to create a cookie, so clicking any internal links resets the text-size. Would you know how to implement this feature?

Thanks a ton for your help!!

Marco

First you need to add those 2 cookies functions: createCookie & readCookie.
Then change this line:
var initSize = 0;

to:
var cookie = readCookie(”initSize”);
initSize = cookie ? cookie : 0;

And finally, in the body of fontSizer function, add after:
initSize = size;

this line:
createCookie(”initSize”, initSize, 365);

That should do it… let me know how it works!

Cheers,
Nick

I tried the code you provided me with, but it doesn’t seem to work- fontSizer doesn’t seem to do anything and FIreFox Error Console spits out “fontSizer not defined”. :( Any ideas? Thanks a lot for your help Nick!

Hey Marco,

Send me the file you are using so I can spot the problem…

Cheers,
Nick

Sorry Nick, pls ignore my previous post. I can’t get that script working on my site anyway.

What would be really cool would be a ‘reset’ button for your script.

Do you have the code for that? :smile:

Thanks again,
Mike

Hey Mike,

You can add another link like this:
<a href=”javascript:fsize(10,’px’,'content’);” rel=”nofollow”>Reset</a> or
<a href=”#” onclick=”fsize(10,’px’,'content’);” rel=”nofollow”>Reset</a>

Great. Thanks Nick! :smile:

Mike

Thanks to providing this code. i was waiting lot more time for this code. thanks again You have done such a wonderful job.

I did not follow the 3rd step in your post. Also if the text is resized in 1 page, will the same setting be applicable to the rest of the pages in the site.Plz help.Thanks in advance.

If you want the text to be resized in all the pages according to current page setting, you need to follow all 3 steps.

Hi

Thanks for a great script.

I have a couple of questions if you could help.

1) I have used the reset code you suggested however when I go from one page to the next after clicking reset it remembers from the cookie the privouse setting.

2) is there a way of apply the font sizer to more than one div id?

Thanks for any help you can give and great code again.

Chris

Hi Chris,

1) Isn’t it how it should work? I mean, just imagine that you set to a very large size, then hit resize and if no cookies are set, then you’ll get the same large size on the next page - not pretty!

2) use the id of the parent of those different divs

Hi

Sorry didn’t explain myself very well. It does what you describe, when you hit the reset link it reduces the font but then when you go to the next page it is back up to the big font as the reset is not either removing or editing the cookie.

I don’t think the reset is setting a cookie.

Thanks
Chris

@Chris

I see - check again the post “Javascript - text resize” and you will find the correct way to set up the reset link.

Thanks yes used the following and worked a treat I was missing the onclick!
Doh.

thanks again for your time.

reset

Useful code, I will be incorporating it into my websites!

That’s great code, but for those of you who use jquery, try out this code:

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;
});
});

Great script, and thanks a lot for putting it on the web. However, Google Chrome doesn’t seem to accept or be able to work with the cookie? It resizes alright, but on the next page the size is back to the orginal size. Whereas in all other browsers the new font size is retained. The only thing I changed is px to em.

Thanks in advance for your help,
Frank

You should remove the path part from the createCookie function.