HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Calculating the font size to fit the width of a website

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
websitethesizecalculatingwidthfontfit

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();
});

$(document).ready(function(){
    $('body').find('*').addClass('wFonte');

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

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

widthFontsReady();

});

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

}

function widthFontsReady(){
    $('.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

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.

Context

StackExchange Code Review Q#19292, answer score: 3

Revisions (0)

No revisions yet.