Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JavaScript to read html / body tag margin-top

I'm trying to read "marginTop" style property from the <html> and <body> tags. Chrome developer tools shows margin-top as set via in-HTML CSS:

<style type="text/css" media="screen">
html { margin-top: 28px !important; }
* html body { margin-top: 28px !important; }
</style>

However, when I try something like this:

console.debug(document.getElementsByTagName('html')[0].style.marginTop);
console.debug(document.getElementsByTagName('body')[0].style.marginTop);

I get empty strings in both cases.

jQuery's offset() function detects margins correctly. Unfortunately, I cannot use jQuery in this case, it has to be pure JavaScript.

I would appreciate if someone could provide some insight on how I can read top margin property off the html and body elements.

like image 747
martynasma Avatar asked Dec 16 '22 15:12

martynasma


2 Answers

You can solve it with:

var element = document.getElementsByTagName('html')[0],
    style = window.getComputedStyle(element),
    marginTop = style.getPropertyValue('margin-top');

jsFiddle

like image 86
Mateusz Rogulski Avatar answered Dec 18 '22 03:12

Mateusz Rogulski


The document already has knowledge about body element, so:

window.getComputedStyle(document.body).getPropertyValue('margin-top');
like image 27
Vladimir Zaets Avatar answered Dec 18 '22 03:12

Vladimir Zaets