jQuery Tip: Quick and Easy Font Resizing
Wednesday, January 7th, 2009
One of the many great features of jQuery is how easy it is to edit the css via a user event, such as a click. We can use this to knowledge to edit any css property we wish. Recently, NETTUTS had a great article that went all out with a font resizing slider bar using the jQuery UI. While this article was certainly in-depth and well done, we want something quick and simple. Today we will create a simple script to allow the user to edit the current font size of an element.
Our Goal
Before starting any project, we need to know what we want to do. We want a simple and quick script to resize the text within a certain element 'on click'.
Basic HTML
First thing we need to do is setup our simple HTML page, we will use the code below for the demo.
<!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" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="author" content="Drew Douglass" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <title>jQuery Font Size Change | Dev-Tips</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script> <script type='text/javascript'> </script> </head> <body> <h2>Text Resizing with jQuery Demo.</h2> <input type='button' value='Larger' id='large' /> <input type='button' value='Smaller' id='small' /> <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p> </body> </html>
Setup some variables
Now it's time to setup some variables to use later on in our script, I'll explain more after the code below.
$(function(){
$('input').click(function(){
var ourText = $('p');
var currFontSize = ourText.css('fontSize');
var finalNum = parseFloat(currFontSize, 10);
var stringEnding = currFontSize.slice(-2);
First we use some shorthand jQuery, which is the same as using document.ready(). Next we will setup some variable to use when the input buttons are clicked. The variable ourText will be our paragraph to re size. The variable currFontSize gets the current font size of the paragraph. The variable finalNum uses the parseFloat function to convert the string into a floating point number (with a base of 10). The variable stringEnding gets the pixels or em ending so we can add it back on later.
Conditional Statements
Next we need to decide what to do depending on the button the user is clicking on.
if(this.id == 'large') {
finalNum *= 1.2;
}
else if (this.id == 'small'){
finalNum /=1.2;
}
ourText.css('fontSize', finalNum + stringEnding);
});
});
The above should be pretty self-explanatory. If they clicked on the large button, we multiply the current font size by 1.2, and if they click on the small button the font size is divided by 1.2.
Full Script
Our final script looks like this:
$(function(){
$('input').click(function(){
var ourText = $('p');
var currFontSize = ourText.css('fontSize');
var finalNum = parseFloat(currFontSize, 10);
var stringEnding = currFontSize.slice(-2);
if(this.id == 'large') {
finalNum *= 1.2;
}
else if (this.id == 'small'){
finalNum /=1.2;
}
ourText.css('fontSize', finalNum + stringEnding);
});
});
And that's it, we now have a quick and simple font resizing script using jQuery. Don't forget to check out the demo below if you want to see it in action.
View the Demo
Update with animation!
Due to the popularity of this article, we have published another font resizing script, this time with animations on the resize. Be sure to check it out 'Font resizing with animation effects.'.
If you enjoyed this article, you might consider subscribing to our rss feed to stay updated with all the latest tips and articles!
Article Sponsored by:
Quench is a premium XHTML and php based theme developed by Drew Douglass of Dev-Tips. Quench is packed full of features and is perfect for a portfolio, blog, or personal web site. It also includes a working contact form and integrates your twitter status on the homepage.
31 Comments
subscribe comments feedTrackbacks/Pingbacks
- jQuery Tip: Font Resizing With Animation Effects | Dev Tips | Become a Better Developer, One Tip at a Time.
- My Little List of jQuery Tips, Tricks and Resources | Moral Fibre
- jQuery Tip: Quick and Easy Font Resizing | Dev Tips | Become a Better Developer, One Tip at a Time. | Squico
- How To Create Your First AJAX and PHP Contact Form | Dev Tips | Become a Better Developer, One Tip at a Time.









This cool, i am learning php so will use it. thanks to you for article and sorry for my english
Your English is just fine, glad you enjoyed the article
Neat little JQuery Font Resize. Good Work!
Here is a nice MooTools version using a slider from David Walsh.
http://davidwalsh.name/mootools-font-size-scroller-cookie-save
Hey Brenelz,
Thanks for the link and your comment! David Walsh is one of my many internet heroes (like I’ve said, I have a huge list I study 5 times a day) so I’ll def. have a look. Thanks again.
Love this one. Works great – nice demo. Thanks for sharing!
Thanks Simon, much appreciated!
Brilliant. Thanks for sharing.
Your welcome. Thanks for calling it brilliant
Hi!! Thanks for your code!!
With a litle bit mod i’m using this js in my first wordpress based portal.
Look at http://www.interativa.uniderp.br/novo/?p=359 (still under construction)
Thank you! []’s
Great to see a real implementation, thanks for your comment and nice work on your site
Drew has done it again! Thanks for this awesome tip!
Hopefully I will be using this in an upcoming website!
Thanks Meshach! Glad you enjoyed it, be sure to show off the website you are working on so we can all see the script in action
Drew, nice work, and I think it’s going to work well in my current design (where the fonts are em-based and not pixel-based). One question: I’m a JS doofus
and I’d rather have clickable text links than form buttons. How would I configure that to work in an anchor element?
Note: that last bit should read:
…in an <a> anchor element.
Let’s see how Wordpress handles that, LOL.
Hi Max,
Thanks for your comment, I’m really glad to hear you found this useful and would like to incorporate it in your design. To do it with links instead of input elements, do something like this:
–Author Edit-see demo link below for full complete code.
Nice. I’m staying up past my bedtime to try this out. Thanks, Drew!
No problem, also just realized I put a ‘#’in front of the
$('a')obviously that shouldn’t be there. If you need any more help just ask as I haven’t tested the revised script I gave youIgnore that last comment, removing that hash mark seems to have done the trick. Woo hoo!
There are a blue million font resizer scripts out there, but almost all of them are crafted to work with pixels. This is much better for my needs. I’ll try it tomorrow in the actual design and if it works–as it should–I’ll post the link. And you definitely get a credit in the design credits/notes page.
Arrgh, no joy. The links are very simple (trying it in a dedicated demo page):
<a href=”#” id=’large’>Larger</a>
<a href=”#” id=’small’>Smaller</a>
Do I need to add some sort of script command in place of the # placeholder?
Again, I appreciate your helpfulness and apologize for my woeful lack of knowledge.
Hey Max,
No worries, take a look at the source code here and that should take care of it
Also, note how in the example we target only the anchor tags wrapped in a div with an id of font_change. This is because we need to return false but don’t want to affect any other links on the page.
Here you go:
http://dev-tips.com/demo/max.html
Drew, it works beautifully. You can see the results here, when I get the code added to all the pages and posted:
Demo Page (listing of all demo pages in demo site)
You’ve really gone over and above the call of duty. Thanks, man, I owe you one.
Your absolutely welcome Max, don’t mention it
I’ll check out your demo soon, looking forward to seeing it!
I tried moving the js into an external file and calling it to the head, doesn’t seem to work externally.
hello, fantastic script.
after a little bit of coding I am sharing with you the “return to the normal” state and the maximum and minimum value. I am new to jquery so maybe it is not exactly the right code- but it works:
$(function(){
$(‘a#sizeBig, a#sizeSmall, a#sizeNormal’).click(function(){
var ourText = $(‘#content’);
var currFontSize = ourText.css(‘fontSize’);
var finalNum = parseFloat(currFontSize, 11);
var stringEnding = currFontSize.slice(-2);
if(this.className == ’sizeBig’ ) {
finalNum *= 1.2;
if (finalNum >= 20) {finalNum = 20;}
}
if (this.className == ’sizeSmall’ ){
finalNum /=1.2;
if (finalNum <= 9) {finalNum = 9;}
}
else if(this.className == ’sizeNormal’ ) {
finalNum = 11;
}
ourText.css(‘fontSize’, finalNum + stringEnding);
return false;
});
});
Could we get this with cookies, the last font size gets stored so it will always display that way..
hey… good tut… thanks for that useful information…
I have had a stupid problem, I don’t know why buttons (I replace standard buttons with background images) have like and dotted outline. I have seen and modified once and again CSS files putting outline:0 but nothing works, it is weird because the outline is only shown in Firefox… do you know how can I solve it??? thanks
Two questions!
1. How about resetting the text to original size?
2. Adding more line-height when text gets larger.