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
I’m curious.. what is the point of doing this in JavaScript? Are there major browsers that are incapable of increasing page text size?
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.
Cool, Can the links be resized too? They didn’t change for me. :)
@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! :)
@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!
@David:
Yes I see that. Good job on having a design that can be fluid when you need it ;)
In light of the problem discussed above I have converted over to a more fluid layout. Now everything resizes as expected :)
Awesome Eric!
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 :-)
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.
Great work oww
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
@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!
great stuff – thanks – please let me know asap : )
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.”
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.
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.
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.
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!
Nice tutorial, I created a similar script that some people might want to take a look at: Change Font Size with JavaScript
Hi Eric,
Can you please tell me what’s wrong with this cookies function, it doesn’t work for me. Thanks!
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!
Genius simplicity.
how about script that reverts the type size back? thanks.
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 ?
Thanks Eric – I like your simplicity approach. Code was superb.
This is fine and dandy but WHERE do you put this code exactly?
nice. thanks.
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.
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.
UPDATE: New article uses MooTools 1.2.4 at http://davidwalsh.name/save-text-size-mootools
Thanks, been looking for a small script like this for ages, also..
it works in Google Chrome
@Isabella Clochard: No problem! Glad to help :)
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
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.
I really like this cms. I use the same blog cms in 6 blogs of my network.
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.
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+.
@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.. :)
Everything is working great, but in IE the Make Text Bigger is not working. Anyone have an idea why?
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
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!
Don’t know what happened to the formatting in my above comment… sorry. It was supposed to have some line breaks in there :-/
How to resize Images Plz do something for that : (
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?
@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.
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:
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.
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
Okay, between code tags this part was invisible:
A
A
A
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!
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!
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
Thank you very much. your suggestion worked for me in % as well.
how to put a limit on the font size when increasing it
With the script above, changing font sizes, I just want to target 1 specific class on my page, however I tried
document.getElementsByClassName('wrapper')
but that doesn’t work. Can anyone advise please? Thanks!Thanks! I found this invaluable when I wanted to provide an option to only zoom a certain div that I injected into the page via JS. (BTW, the link to the simple, unobtrusive example does not work….)
Unfortunately I’ve just tried this on this very page and it only changes very few parts of the page… The code blocks stay the same, as well as sidebar, menu, buttons.
This makes a case for using
rem
wherever possible, so child elements adjust to changes to the parent element.