G
G
Genome_X2012-06-27 09:39:39
JavaScript
Genome_X, 2012-06-27 09:39:39

Incorrect behavior of Google Chrome when calculating image width. How to fix?

Actually a subject.
I 'm using the latest version of jQuery, the page has an image and there is a code like: Only this code works somehow crookedly in Google Chrome (latest version), while in other browsers everything works okay. What is inoperability? I write something like console.log(width), reload the page, "0" falls into the console. I reboot with F5, no result. However, if you place the cursor exactly in the address bar and press Enter, everything magically starts working right there, i.e. the value I need appears in the console. But if you press F5 again, the result is reset again. What nonsense? How to fix? And why only Chrome suffers? Even IE7 works correctly.

var width = $('img').width();<br>



Answer the question

In order to leave comments, you need to log in

4 answer(s)
F
freeek, 2012-06-27
@Genome_X

In document.ready, images may not be loaded, perhaps when they are not in the cache, you see 0.
Try:

var img_width = 0;
$(window).load(function() {
    img_width+=$('img').width();
});

G
Genome_X, 2012-06-27
@Genome_X

Arrrrr!
In general, note to all interested: read the difference between $(document).ready and $(window).load

E
Evengard, 2012-06-27
@Evengard

Have you tried wrapping it in onload?

T
TheMengzor, 2012-06-27
@TheMengzor

Because the image hasn't loaded yet.
function imageWidth(){
return $('img').width();
}
<img src="http://example.net/picture.jpg" />
var img = new Image();
img.src = " example.net/picture.jpg";
img.onload = imageWidth;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question