# Calculating the font size to fit the width of a website

Posted on

Problem

I created a function to calculate the font size to fit the width of the website I’m doing. I believe the code is a bit ugly and could use some improvement by creating a more logical function, faster and less heavy.

Can someone look at the code and comment on it for my own improvement?

``````//Script jquery

\$(window).resize(function() {
newWidthGhost = \$('#ghostFontes').width();
widthFontsResize();
});

\$('.wFonte').each(function(i, el){
fontHeight[i] = \$(el).css('font-size');
});

oldWidthGhost = \$('#ghostFontes').width(); // TAMANHO WIDTH;

});

function widthFontsResize(){
\$('.wFonte').each(function(i, el){
nFonte['e'+i] = parseInt((newWidthGhost * nFonte[i]) / oldWidthGhost);
\$(el).css({'font-size': nFonte['e'+i]+'px'});
});

}

\$('.wFonte').each(function(i, el){
nFontHeigth[i] = parseInt(fontHeight[i].substr(0,2));
nFonte[i] = parseInt((oldWidthGhost * nFontHeigth[i]) / 1586);
\$(el).css({'font-size': nFonte[i]+'px'});
});

}
``````

Solution

From what I understand from your code, you are scaling the original fonts as the window resizes, am I correct?

For a totally better approach, use the native `em` scaling technique. That is, change the parent `em` measurement, you also change the children within it. Here’s sample code which is exponentially shorter than yours:

``````\$(function() {
//caching frequently used elements and values
var ghostFontes = \$('#ghostFontes'),
\$window = \$(window),
originalWidth = ghostFontes.width();

\$window.on('resize', function() {
//scale the parent container's em measurement
//with the ratio of width to original width
ghostFontes.css('font-size',(ghostFontes.width() / originalWidth)+'em');

});
});​
``````

# Use strict-mode

Start your code with `"use strict";`:
https://stackoverflow.com/questions/1335851/what-does-use-strict-do-in-javascript-and-what-is-the-reasoning-behind-it

# Don’t pollute the global namespace

When you don’t use `var x;` to declare a variable, it is implicitly declared in the global namespace. If another script does the same, both scripts will be using the same variable.

It is not very easy for this to happen with an odd name like `newWidthGhost`, but `fontHeight` sounds like a better candidate for these surprises.

# Run the code through JSLint

Run your code through JSlint, and try to understand the errors and suggestions it gives you.

That alone will greatly improve the quality of your code.