Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery occasionally returns zero height and width on image

I am observing an unusual behavior. I have a floating dialogue box in which I am placing an image. I want to get the image size using jquery and resize its div container to the appropriate size. It works fairly well, but the function occasionally returns zeros as the image sizes.

$('#dialogueContainer').html('<div class="dialogue"><img src="/photos/' + file + '" id="lightImage" /></div>');

var imageHeight = $('#lightImage').height();
var imageWidth = $('#lightImage').width();

console.log(imageHeight + 'x' + imageWidth); //<-- This occasionally returns "0x0"

I suspect that the image may not be ready in the DOM when jquery attempts to measure its height and width. Any thoughts?

like image 487
Tanoro Avatar asked Feb 10 '12 22:02

Tanoro


1 Answers

You're right, the image is not loaded.

Worst, in IE, sometimes the size reported is something like 40x60 (the small icon you see when the image is not loaded yet).

jQuery reports that the load event can be used with images: http://api.jquery.com/load-event/

I tried a long time ago to solve this problem, cross browser, and I ended up polling the image sizes to trigger a custom "load" event.

Thanks

like image 180
Mike Gleason jr Couturier Avatar answered Oct 23 '22 19:10

Mike Gleason jr Couturier