mehdok
mehdok

Reputation: 1608

javascript change font size and line space encounter

I have 4 function in javascript for increasing font size and decreasing font size, increasing line space and decreasing line space. these functions working well, But if i increase font size 2 times, then click on decrease line space the line space will be increased!!

i'm too confuse, any help would be appreciated.

$('#incFont').on('click', function()
{
    var style = getComputedStyle(document.body);
    if (style.fontSize.match(/px$/) === null)
    {
        document.body.style.fontSize = "1.0em";
    }

    document.body.style.fontSize = (parseFloat(style.fontSize) * 1.2 / 16) + "em";
});

$('#decFont').on('click', function()
{
    var style = getComputedStyle(document.body);
    if (style.fontSize.match(/px$/) === null)
    {
        document.body.style.fontSize = "1.0em";
    }

    document.body.style.fontSize = (parseFloat(style.fontSize) * 0.8 / 16) + "em";
});

$('#incLine').on('click', function()
{
    var style = getComputedStyle(document.body);
    if (style.lineHeight.match(/px$/) === null)
    {
        document.body.style.lineHeight = "1.0em";
    }
    document.body.style.lineHeight = (parseFloat(style.lineHeight) * 1.2 / 16) + "em";
});

$('#decLine').on('click', function()
{
    var style = getComputedStyle(document.body);
    if (style.lineHeight.match(/px$/) === null)
    {
        document.body.style.lineHeight = "1.0em";
    }
    document.body.style.lineHeight = (parseFloat(style.lineHeight) * 0.8 / 16) + "em";
});

jsfiddle

Upvotes: 1

Views: 364

Answers (1)

lagerone
lagerone

Reputation: 1767

This happens because you use em, which is a font relative length. Because of this you also increase the lineHeigth everytime you increase the fontSize.

Your formula for decreasing lineHeight will not work unless you add support for and keep track of the number of times you increased the font size.

To keep it simple use px or rem instead.

Upvotes: 1

Related Questions