Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css style not loaded when window.onload is triggered

Here is my problem : the css style is not initialised when window.onload is triggered.

 <div id="foo"></div>

css file

 #foo {
    height: 200px
 }

js file

window.onload = function(){
     console.log(document.getElementById('foo').style.height);
};

the console displays : ""

the style must be in a different file, if the style attribute is used (style="height=200px") it works.

like image 855
IxDay Avatar asked Oct 21 '25 04:10

IxDay


2 Answers

.style.height does not show styles that come from CSS rules. It only returns styles that have been explicitly set on that object, either in the HTML or via javascript, not styles inherited from CSS rules.

Instead, you must use window.getComputedStyle(). See the MDN doc for more details on how to use getComputedStyle() properly. Here's one example:

window.getComputedStyle(document.getElementById('foo'),null).getPropertyValue("height");

Note: for older versions of IE, you have to either install a polyfill for getComputedStyle or use el.currentStyle.

like image 126
jfriend00 Avatar answered Oct 22 '25 18:10

jfriend00


Element.style will only be set for inline styles(<div id="foo" style="height: 200px"></div>), to get the computed style use window.getComputedStyle

window.getComputedStyle(document.getElementById("foo"), null).getPropertyValue('height')
like image 37
Musa Avatar answered Oct 22 '25 20:10

Musa