Change Text Size On Click With JavaScript

This post was authored by Eric Wendelin. To learn more about Eric, click here.

A lot of blogs and websites that have a wide range of users tend to have buttons or images that change the text size for easier readability. This can easily be implemented with a bit of JavaScript and some HTML to attach it to. There are libraries out there that do this, but in many cases it is likely overkill. Simplicity is generally better where possible.

The Text-Resizing JavaScript Function

function resizeText(multiplier) {
  if (document.body.style.fontSize == "") {
    document.body.style.fontSize = "1.0em";
  }
  document.body.style.fontSize = parseFloat(document.body.style.fontSize) + (multiplier * 0.2) + "em";
}

Note that line 2 in the code above requires that you specify font-size on the <html> element (it is OK to have a font-size that is specified in pixels). Alright let's see our options for using the resizeText() function.

The HTML (I use images here but you can use any HTML element)

<img id="plustext" alt="Increase text size" src="images/makeTextBigger.jpg" onclick="resizeText(1)" />
<img id="minustext" alt="Decrease text size" src="images/makeTextSmaller.jpg" onclick="resizeText(-1)" />

You can of course unobtrusively add the events like this:

The Unobtrusive Way Using JavaScript

$("plustext").addEvent("click", function() {resizeText(1);});
$("minustext").addEvent("click", function() {resizeText(-1);});

Here's a simple example of this all put together. This works flawlessly on at least IE, Firefox, Opera, and Safari (others not fully tested, please give feedback :)

I'm sure you readers can think of some improvements so let's see some in the comments!

About Eric Wendelin

Eric Wendelin is a software engineer for Sun Microsystems. When he's not doing super-secret programming for Sun, he plays indoor soccer, playing Wii with his friends, and cheering on the Colorado Avalanche. He also writes a blog on JavaScript, CSS, Java, and Productivity at eriwen.com


Comments

  1. Andrew Medico

    I’m curious.. what is the point of doing this in JavaScript? Are there major browsers that are incapable of increasing page text size?

  2. david

    I think it’s good to do this in javascript because many users may not know how to change the text size using the browser’s menu. Believe me, you’d be surprised how much I need to explain to customers about their browsers.

  3. Duuude

    Cool, Can the links be resized too? They didn’t change for me. :)

  4. Eric Wendelin

    @Duuude:

    This method actually does work for links and stuff, but my site is a bad example because there is hacky stuff in place preventing certain nodes from being resized.

    I encourage you to cut and paste the code into your Firebug console (replacing “multiplier” with a 1) and convince yourself of this, proving how accessible David’s site is compared to mine.

    A lesson in JavaScript and a lesson in accessibility. What more could you ask for! :)

  5. david

    @Eric: Yep, I went with “em’s” for my theme’s font. How unprogrammer like to use a varying-sized font — we want complete control!

  6. Eric Wendelin

    @David:

    Yes I see that. Good job on having a design that can be fluid when you need it ;)

  7. Eric Wendelin

    In light of the problem discussed above I have converted over to a more fluid layout. Now everything resizes as expected :)

  8. david

    Awesome Eric!

  9. Ian Lloyd

    Increase the font size, go to another web site and … back to small text
    Increase the font size, follow a link to another web page on same site and … back to small text

    These ideas seem like they’re worthwhile at first, but they are only any use to your own site. The user never actually learns that they could resize the text for *any* site.

    I would recommend teaching the user how to use the tool they have in front of them, so instead of it triggering some JavaScript, show then how to do it:

    http://accessify.com/news/2007/09/teach-a-man-to-fish-or-how-to-resize-text/

    Personally, I never bother with on-page tools like this … because I don;t need to :-)

  10. david

    Ian: I see your point. It may be a good idea to add a cookie to this functionality so that the page remembers the size.

  11. Muhammad Usman

    Great work oww

  12. Dan

    Hi

    I love it but i need it to be persistent – can you add an example with cookie so that site experience sticks to chosen size please

  13. david

    @Dan: Beat you to that request. Eric is in the process of creating a “part 2″ of sorts that saves the font information in a cookie and uses that value on every page. Stay tuned!

  14. Dan

    great stuff – thanks – please let me know asap : )

  15. Alex

    This is not a bad idea, I’ve stumbled upon it when got a request to put the JS resizing func on a clients website… too lazy to write my own, and theres no need, so here I am.

    Though, I do think that this is kind of retarded, there is a tool in a browser… use it! If people dont know how, then they should learn or not, their choice…

    I recall a quote from bash.org, it went something like this:
    “the problem with people is stupidity! I say, take the safety labels off of everything and let the problem work itself out.”

  16. Dan

    Yeah I agree that most people are stupid but the client wants it (the most stupid people of all) so if anyone figures a way then i’ll help stupid people think less.

  17. Luke

    I have built a few of these javascript resizers, usually adding something new to each revision. One example of this can be found at http://www.cppht.com which is a housing association site which I built.

    The problem I found was that I needed a javascript text resizer which allowed for varying text sizes across the site, and kept htem all in proportion to each other when they were resized (i.e. I didnt want everything on the site to be the same font size).

    To get round this, I simply used a variable which held the current adjustment value (i.e. +2 or -4) which I then used to manipulate each tag as I got to it. The biggest downside to my script (which I havent been able to overcome yet) is that every element on the site must include its own ‘style=”font-size: px;” ‘ tag in order to resize. The settings in my CSS stylesheet dont appear to have an effect when the resize functions looks at the element.

    Any ideas? If I can solve this problem then I think my script would be complete and very robust! I will of course provide a copy of the script to anyone that wants to take a look.

  18. Luke

    P.S. Ignore the fact that the example site given spreads horribly across the screen! This is easily solved in sites I have built since.

  19. tofu

    great script! is there a way to limit the amount of clicks – for example, a user can only increase 2 times, and decrease 1?

    thanks!

  20. Iwek

    Nice tutorial, I created a similar script that some people might want to take a look at: Change Font Size with JavaScript

  21. CaPheMotMinh

    Hi Eric,

    Can you please tell me what’s wrong with this cookies function, it doesn’t work for me. Thanks!

    var min=10;
    var incrementNum = 2
    var defaultSize = 12;
    var max=24;

    createCookie(‘txtsize’,defaultSize);
    var standard=(readCookie(‘txtsize’)==null)?defaultSize:readCookie(‘txtsize’);

    function increaseFontSize() {

    var p = document.getElementsByTagName(‘div’);

    for(i=0;i<p.length;i++) {

    if(p[i].style.fontSize) {

    var s = parseInt(p[i].style.fontSize.replace(“px”,”"));

    } else {

    var s = standard;

    }

    if(s < max) {

    s += incrementNum ;

    }

    p[i].style.fontSize = s+”px”;

    }

    };

    function resetFontSize() {

    var p = document.getElementsByTagName(‘div’);

    for(i=0;i<p.length;i++) {

    p[i].style.fontSize = standard+”px”;

    }

    };

    function decreaseFontSize() {

    var p = document.getElementsByTagName(‘div’);

    for(i=0;i<p.length;i++) {

    if(p[i].style.fontSize) {

    var s = parseInt(p[i].style.fontSize.replace(“px”,”"));

    } else {

    var s = standard;

    }

    if(s > min) {

    s -= incrementNum ;

    }

    p[i].style.fontSize = s+”px”;

    }

    };

    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[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;

    }

  22. webboy

    is there a way to resize all the page contents together with text like images, flash, etc?

    like the coded version of ctrl+ and ctrl- ?

    but i must agree this script is cool!

  23. Sklep Zoologiczny

    Genius simplicity.

  24. kdesign

    how about script that reverts the type size back? thanks.

  25. Alok Jain

    Nice Post :)

    However this functionality have issue with images.

    If we add image size in em’s it’s difficult to calculate exact size in em and apart from that background images don’t get resized, which cause a design breakdown.

    Any Thoughts on this ?

  26. Simon

    Thanks Eric – I like your simplicity approach. Code was superb.

  27. Chris

    This is fine and dandy but WHERE do you put this code exactly?

  28. jin

    nice. thanks.

  29. Matt Heiner

    Just an idea, this was very helpful, but for some people, it might be better to do a fontsize change based on id, so the font for the entire site doesn’t change, just the content does.

    function resizeText(multiplier) {
    if (document.getElementById(‘main-content’).style.fontSize == “”) {
    document.getElementById(‘main-content’).style.fontSize = “1.0em”;
    }
    document.getElementById(‘main-content’).style.fontSize = parseFloat(document.getElementById(‘main-content’).style.fontSize) + (multiplier * 0.2) + “em”;
    }

  30. Isabella Clochard

    Thank you. I was beginning to despair of ever finding a font-size script that would work in Explorer, Opera, and Firefox, but yours works flawlessly in all three browsers.

  31. Eric Wendelin

    UPDATE: New article uses MooTools 1.2.4 at http://davidwalsh.name/save-text-size-mootools

  32. Chris

    Thanks, been looking for a small script like this for ages, also..

    it works in Google Chrome

  33. Matt Heiner

    @Isabella Clochard: No problem! Glad to help :)

  34. Julian Lafforgue

    First, thankx for this nice little tut.
    I´m trying make it work for a css class, insted of a body style, and i can´t get it working.
    help please please please

  35. John

    Another approach would be to use JavaScript to load specific style sheets based on what size font has been selected. In this way, you can maintain control over the full layout. You might have 4 different style sheets, each on giving the end user the precise layout that you want them to have.

    You can also use this method to automatically make your content fit when the user resizes the page in a material way.

  36. busy do Niemiec z Tczewa

    I really like this cms. I use the same blog cms in 6 blogs of my network.

  37. Büyü Çeşitleri

    Another approach would be to use JavaScript to load specific style sheets based on what size font has been selected. In this way, you can maintain control over the full layout. You might have 4 different style sheets, each on giving the end user the precise layout that you want them to have.

    You can also use this method to automatically make your content fit when the user resizes the page in a material way.

  38. Anil Kumar

    I found this is the most appropriate method for embedded IE in Windows Mobile, which follows IE5 standards and browser based zoom level came only IE 5.5+.

  39. Dan

    @Ian Lloyd: Good point but a lot of people prefer to do this with only one click, and changing the font size using the browser tools can make other website look bad so then they have to change it back.. :)

  40. Sierra

    Everything is working great, but in IE the Make Text Bigger is not working. Anyone have an idea why?

  41. austin

    how can the JS be modified to target specific tags within the body.
    I tried:
    document.body.h1.style.fontSize
    instead of:
    document.body.style.fontSize

    no luck

  42. rn5150

    Thanks for the great script!

    However, I am looking for a way to modify the script so that it works, as designed, regardless of the units being used in the CSS definitions? As the script is written, unless ‘em’s are used to define the font-size, merging, etc., the properties will not be affected.

    For example, if I set the following CSS:
    p {font-size: 0.9em; margin-bottom: 10px;}
    the font size will change, but not the margin. And if I were to set:
    p {font-size: 14px; margin-bottom: 10px;}
    nothing would change.

    Am I missing something simple, or is this functionality more difficult than I am anticipating?

    Thanks, in advance!

  43. rn5150

    Don’t know what happened to the formatting in my above comment… sorry. It was supposed to have some line breaks in there :-/

  44. Inder J

    How to resize Images Plz do something for that : (


Be Heard!

Share your thoughts without being a jerk! And wrap your code in <code> tags, f00!

Name*:
Email*:
Website: