Jquery; Chrome Image Width and Height = 0 for new Image()

Tourshi picture Tourshi · Mar 4, 2011 · Viewed 7.6k times · Source

Im having trouble getting Chrome to recognize an Image width or height after the DOM has loaded. The Image is dynamically loaded through phpThumb script (which resizes the image). If I take away the dynamic url and just replace it with the Image's direct url I get no issues and everything works in Chrome but with the dynamic url, chrome doesn't seem to be able to calculate the image width or height.

Anyone have any experience with this? Its doing my head in.

The code in question is :

var theImage     = new Image();
theImage.src     = $image.attr('src');
var imgwidth     = theImage.width;
var imgheight    = theImage.height;

Where imgwidth = 0; for chrome, yet IE, Firefox both report the correct size.

Answer

mike picture mike · Jun 4, 2011

The right code is .onload and the following function:

var theImage     = new Image();
theImage.src     = $image.attr('src');
theImage.onload = function(){
    var imgwidth     = $(this).width;
    var imgheight    = $(this).height; 
});