1

I'm trying to get the height of an image with jquery

$(document).ready(function() {
    alert($('#image').height());
})

Very basic. However I'm confused.
If I press F5 I get the following result:
Firefox: 383px
IE 8: 30px
Chrome: 0px

If I go to the page via a link:
Firefox: 383px
IE 8: 383px
Chrome: 383px

383 is obviously the correct value. But why do I get the wrong value upon refresh?

Trufa
  • 39,971
  • 43
  • 126
  • 190
Anders
  • 217
  • 3
  • 11

3 Answers3

3

document.ready fires after the DOM has loaded, but not necessarily after the images and CSS have loaded. If you run that code on window.onload, you should get consistent results across the browsers.

Try using jQuery's load handler instead:

$(window).load(function() {
    alert($('#image').height());
})
Emmett
  • 14,035
  • 12
  • 56
  • 81
  • Very nice! I guess the picture was cached when I followed a link and therefore it was able to determine size in all browsers. – Anders Dec 11 '10 at 19:11
3

Try waiting until the image is completely loaded

    var img = document.getElementById("image");
    img.onload = function () {
    alert($('#image').height());
    };
Enrique
  • 9,920
  • 7
  • 47
  • 59
  • IE has some known issues with image.onload: http://stackoverflow.com/questions/198892/img-onload-doesnt-work-well-in-ie7 – Emmett Dec 11 '10 at 19:09
0
$(document).ready(function() {

    $('#image').bind("load", function() {
       alert($('#image').height());
    });

})
andres descalzo
  • 14,887
  • 13
  • 64
  • 115