Simple code:
$(document).ready(function(){
console.log($('.slide-background').width());
});
and simple html:
<div class="testdiv">
<img class="slide-background" src="img/slide.png"/>
</div>
As well as simple CSS:
body {
margin: 0; padding: 0;
height: 100%; width: 100%;
}
html {
margin: 0; padding: 0;
height: 100%; width: 100%;
}
.testdiv {
overflow: hidden;
width: 100%;
height: 100%;
background-color: black;
}
Why on earth does it output the width whenever it wants? Sometimes the width actually gets logged, however most of the time a 0 is returned.
In jQuery
$(document).ready()runs code when the DOM is loaded (which does not include images),$(window).load()runs code when everything is loaded.Simply put, the image width is 0 because it hasn’t loaded at the point your code is running.
Use
$(window).load()instead.