Why does the width value go to zero when the page is refreshed in chrome?

I wrote jQuery code where I get the width of the images on the screen and store them in a variable. Then I registered this variable in the console to see its value. When the page is loaded for the first time it displays the correct value, however if I press F5 it displays 0 as the width.

Here's the HTML:

    <body>
        <img src="img1.jpg" alt="image">
        <img src="img1.jpg" alt="image">
        <script type="text/javascript" src="script.js"></script>
    </body>

      

Here's the jQuery code (script.js):

    jQuery(document).ready(function($) {
        var imgs = $('img');
        var width = imgs[0].width;
        console.log(width);
    });

      

The console displays 600

when the page is loaded for the first time, but when I press F5 it displays 0

. Why is this so?

+3


source to share


2 answers


The jQuery(document).ready()

time is not guaranteed upload images. Images must be uploaded to get their width. Images are loaded asynchronously and may end after firing jQuery(document).ready()

.

To know for sure that an image is loaded, you need to have a handler onload

for that particular image so you can know when it is specifically loaded, or you only need to check the width of the image when all images in the page are loaded with window.onload

or in jQuery $(window).load(fn)

.

The simplest thing would be to change the code:

jQuery(window).load(function() {
    var imgs = jQuery('img');
    var width = imgs[0].width;
    console.log(width);
});

      



Personally, I would recommend that you use jQuery methods .height()

and things .width()

like this:

jQuery(window).load(function() {
    var imgs = jQuery('img');
    var width = imgs.eq(0).width();
    console.log(width);
});

      

You can see this working here: http://jsfiddle.net/jfriend00/D4CyN/

+7


source


If you know the dimensions of the image, place them in the markup:

<img src="img1.jpg" width="600" height="…">

      



Then you will never get the width 0

.: D

0


source







All Articles