Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript change line height of body

I have a function that change lineHeight of body (i need to change line height of all elements):

if (document.body.style.lineHeight == "")
{ 
    document.body.style.lineHeight = "1.0em";
}
document.body.style.lineHeight = parseFloat(document.body.style.lineHeight) + (0.4) + "em";

If the document hasn't any line-height in it's css this code works perfectly and all line height of elements will be increased, BUT there is strange behavior in some case:

1) the document.body.style.lineHeight == "" is always true even if the body in css has line-height!!!

2) if any of the elements has line-height in CSS this code will fail to change line height. i can get document.body.style.lineHeight value and i can see that it increase BUT nothing change in document! (no visual effect)

any help would be appreciated.

like image 559
mehdok Avatar asked Oct 19 '22 12:10

mehdok


1 Answers

As already mentioned in the comments, you need window.getComputedStyle() (or just getComputedStyle()) to retrieve the actually applied style of an element, because element.style will only return the contents of the HTML style attribute.

Note however, that will not be the literal value you assigned it (like 1.5em), but the equivalent in pixels (1em = 16px by the way). The returned value will also not be a number, but a string containing the suffix px.

Also note that the default value will not be "", but "normal".
But it could also be "initial" or "inherit", so instead of checking its actual value, I suggest just checking whether the string ends in px.

So your code should probably look like:

var style = getComputedStyle(document.body);
if (style.lineHeight.match(/px$/) === null)
{ 
    document.body.style.lineHeight = "1.0em";
}
else
{
    document.body.style.lineHeight = (parseFloat(style.lineHeight) / 16) + (0.4) + "em";
}

Also: Fiddle.

And last, note that if you specify a percentage as line height, there is no way to retrieve that value (other than parsing $('style').innerHTML yourself of course), you will only get the pixel equivalent at the time your function runs.


As for your question how to apply the line height to all elements, simply inject a <style> tag in head, containing CSS like:

*
{
    line-height: 1.0em !important;
}

So the snippet above would look something like this:

var tag = document.createElement('style');
var style = getComputedStyle(document.body);
if (style.lineHeight.match(/px$/) === null)
{
    tag.innerHTML = '* { line-height: 1.0em !important; }';
}
else
{
    tag.innerHTML = '* { line-height: ' + (parseFloat(style.lineHeight) / 16 + 0.4) + 'em !important; }';
}
document.head.appendChild(tag);

Of course this will not work if there are more specific selectors with !important already, but otherwise it will even override inline style attributes.

See updated fiddle.

like image 121
Siguza Avatar answered Oct 27 '22 16:10

Siguza