JQuery.width () sometimes works; sometimes not?

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>

      

Like plain 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 does it output the width when it wants? Sometimes the width is actually recorded, however most of the time 0 is returned.

+3


source to share


3 answers


JQuery $(document).ready()

runs the code when the DOM is loaded (which doesn't include images), $(window).load()

runs the code when everything is loaded.

Simply put, the image width is 0 because it is not loaded at the point your code is running at.



Use $(window).load()

instead.

+7


source


The DOM is ready, but your image is still displayed by the browser.



var $image = $('.testdiv img');

var img = new Image();          // in memory image
img.src = $image[0].src;        // set SRC
img.onload = function(){        // as soon it loaded
   alert( img.width ) ;         // WORKS!
}

      

+5


source


As the width is unknown until the image is loaded.

As the W3C recommends, you must set the width

and attributes height

for the <img>

correct width and height to be shown (and known) before the image finishes loading. If you have a very large image, your layout can be completely confusing so that it doesn't take up space before it loads.

+3


source







All Articles