image height using jquery in chrome problem image height using jquery in chrome problem google-chrome google-chrome

image height using jquery in chrome problem


As Josh mentioned, if the image has not fully loaded yet, jQuery won't know what the dimensions are yet. Try something like this to ensure you're only attempting to access it's dimensions after the image has been completely loaded:

var img = new Image();$(img).load( function() {    //-- you can determine the height before adding to the DOM    alert("height: " + img.height);    //-- or you can add it first...    $('body').append(img);    //-- and then check    alert($('body img').height());}).error( function() {    //-- this will fire if the URL is invalid, or some other loading error occurs    alert("DANGER!... DANGER!...");});$(img).attr('src', "http://sstatic.net/so/img/logo.png");


My assumption is that this function is being called before the image is finished loading. Can you try putting a delay on the function to see if this is actually the case? If this is the case, you can cheat by using a timer before running the function.

It is a bit more complicated to detect when an image has been loaded. Have a look at this script for some ideas -- maybe it would work for you.


Preloading the image and setting up a callback function might be what you're looking for:

// simple image preloaderfunction getHeight(el,fn) {    var img = new Image();    img.onload = function() { fn(img.height); };    img.src = el.attr("src");}$("img").each(function(){    getHeight($(this),function(h){        // what you need to do with the height value here        alert(h);    });});