jQuery (JavaScript) Font Resize

// May 26th, 2009 // Code

Here is a way to resize text with javascript. Calling these 2 functions from clicks on images or button is easy. Just add a click event to call the functions as needed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function increaseFont()
{
jQuery('p,h1,h2,h3,h4,h5,td,li a').each(function(){
var oldf = parseInt( jQuery(this).css('font-size') );
var oldl = parseInt( jQuery(this).css('line-height') );
jQuery(this).css({
'font-size' : oldf + 2 + 'px',
'line-height' : oldl + 2 + 'px'
});
});
}
 
function decreaseFont()
{
jQuery('p,h1,h2,h3,h4,h5,td,li a').each(function(){
var oldf = parseFloat( jQuery(this).css('font-size') );
var oldl = parseFloat( jQuery(this).css('line-height') );
jQuery(this).css({
'font-size' : oldf - 2 + 'px',
'line-height' : oldl - 2 + 'px'
});
});
}

This will take all the specified elements and increase or decrease whatever their line-height and font-size is by 2. A bug that I found with IE was that since I hadn’t declared a specific font-size for the elements IE returned the font-size as undefined and when I converted it to a integer and applying the new font-size I was getting sizes at over 600px. Firefox and Safari was of course doing what I wanted and was nicely inheriting their font-sizes in the DOM properly.

It’s a bit of a panicky solution and if you are implementing this kind function in a project and you know about it from the beginning, you can set the font-size on the body element and do all the other fonts and line-heights in “em”. Then you just have to resize the body font-size.

1
2
3
4
5
6
7
8
9
10
11
function increaseFont()
{
var oldf = parseInt( jQuery(this).css('font-size') );
jQuery('body').css('font-size', oldf + 2 + 'px');
}
 
function decreaseFont()
{
var oldf = parseInt( jQuery(this).css('font-size') );
jQuery('body').css('font-size', oldf - 2 + 'px');
}

Leave a Reply

You must be logged in to post a comment.