O'Reilly

Change Text Size On Click With JavaScript

By on  

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

Track.js Error Reporting

Recent Features

  • CSS @supports

    Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn't been available within CSS.  What we end up doing is repeating the same properties multiple times with each browser prefix.  Yuck.  Another thing we...

  • Responsive and Infinitely Scalable JS Animations

    Back in late 2012 it was not easy to find open source projects using requestAnimationFrame() – this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...

Incredible Demos

  • Fancy FAQs with jQuery Sliders

    Frequently asked questions can be super boring, right? They don't have to be! I've already shown you how to create fancy FAQs with MooTools -- here's how to create the same effect using jQuery. The HTML Simply a series of H3s and DIVs wrapper...

  • Create a Brilliant Sprited, CSS-Powered Firefox Animation

    Mozilla recently formally announced Firefox OS and its partners at Mobile World Congress and I couldn't be more excited.  Firefox OS is going to change the lives of people in developing countries, hopefully making a name for itself in the US as well.  The...

Discussion

  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. 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. @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. @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. @David:

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

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

  8. Awesome Eric!

  9. 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. 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. Great work oww

  12. 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. @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. 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. 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. 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. 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. Genius simplicity.

  24. kdesign

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

  25. 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. 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. 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. UPDATE: New article uses MooTools 1.2.4 at http://davidwalsh.name/save-text-size-mootools

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

    it works in Google Chrome

  33. @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. 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. I really like this cms. I use the same blog cms in 6 blogs of my network.

  37. 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. 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. 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. How to resize Images Plz do something for that : (

  45. This script works okay as long as the user does not discover the browser’s built-in font size options (such as in IE’s View menu. Therefore the script should not only resize the text but also dequately change the selected option in the View menu. Is that possible?

  46. @David Walsh

    David, it’s not okay (what you stated in your article) to use pixels initially. On the html-page (or in the style sheet) font sizes must be in ’em’ (or percent perhaps, but I never use that).

    In my previous post ‘dequately change’ should be read as ‘adequately change’of course.

  47. Okay, finally I got it the way I want. It may look a bit different, but without having found the resizer code presented here, I would never been able to write my own variant. So, thank you very much!

    Originally my default font had the size of 12 pixels (which is approximately 10 points, the standard size used in newspaper printing – I’m a retired journalist, that’s why). Most popular browsers use a 16 pixels letter as their default font. To decrease this to “my” 12, in my stylesheet I downgraded the body font to 75 percent. This downgrades “1em” from 16 to 12 pixels. Furthermore I changed all the pixel values for fonts used inside the body to em, so “12px” became “1em”, “10px” is now “0.835em” et cetera. Note that an a-link not having the href-attribute, does not automatically change the mouse cursor into a pointer!

    Here is the relevant code in the style sheet:

    body {
      height: 100%;  
      background-color:.......; 
      margin: 0; 
      padding: 0;
      font-family: blabla;
      font-size: 75%;
    } 
    

    And this is the code for the html-pages, including a small picture of a pair of spectacles (‘bril’ in Dutch). The titles mean: Default font, Larger font and largest font. And yes, the 3 click-on A’s don’t resize.

     
    A 
    A 
    A
    

    And finally, here you may want to try my first test page: http://weblog.egbertzijlema.nl/resize.php. It’s in Dutch, so most of you cannot read it, but the resizing works as far as I can see.

    Regards,
    Egbert

  48. Okay, between code tags this part was invisible:

    A
    A
    A

  49. Hi there! I am new to javascript. Can anyone help me out in setting a maximum and minimum text size for this script?

    Thanks in advance!

  50. Hi,
    this is a great little snippet and works perfectly for my purposes, however is there a bit of script I can add to yours to set a maximum percentage increase in the text size? i.e. the text can be made larger but no larger than 200% of its original?

    thanks!

  51. Bulut Toprak

    Hi,

    thanks for this snippet. this is how i used your snippet to zoom instead of manipulating the font size in case anyone needs it

    function resizeText(multiplier) {
      if (!document.body.style.zoom == "100%") {
        document.body.style.zoom = "100%";
      }
      document.body.style.fontSize = parseFloat(document.body.style.zoom) + (multiplier * 10) + "%";
    }
    
  52. Nimmi Thomas

    Thank you very much. your suggestion worked for me in % as well.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Sort git Branches by Date

    I'll be first person to admit I don't do as much git repository maintenance as I should.  I rarely delete branches which have been merged, so a git branch execution shows me a mile-long list of branches that likely aren't relevant.  The best way to find branches I've recently...

  • Best Tools and Resources for Web Professionals in 2015

    Looking for the right resources to help you satisfy the needs of your clients? On the lookout for the best tools to help you increase your revenue? Searching for the right software to help you improve your business? Well, then you’ve come to the right place....

  • JavaScript Polling

    Polling with JavaScript is one of those ugly but important functions within advanced front-end user experience and testing practices.  Sometimes there isn't the event you can hook into to signify that a given task is complete, so you need to get your hands dirty and simply poll for...

  • OSCON Portland:  Conference Giveaway and Discount!

    O'Reilly puts on the best web industry conferences in the world.  These conferences include Fluent Conference, Velocity Conference, and the upcoming OSCON in Portland, Oregon from July 20-24.  Open Source Convention (OSCON) is a conference that focuses specifically on open source developers and the tools and possibilities...

  • Prevent Chrome from Translating a Page

    A while back I shared my favorite Google Chrome extension:  Google Art Project.  I've enjoyed seeing beautiful art when I open a new tab -- it's brought genuine happiness to my day, however small that happiness may be.  About a week ago, however, the art presented had...