Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery width() returns 0 [duplicate]

Possible Duplicate:
Official way to ask jQuery wait for all images to load before executing something

I'm writing a jQuery plugin that handles a bunch of image animations with a simple call to the plugin function (something like $("#image1").anims() where #image1 is an image), however as part of the plugin's functionality I use $(this).width() to get the width of the image right at the start of the function call.

But, since the plugin function is called in $(document).ready, it's trying to get the width of the image before the image has loaded, so it's always returning 0. Is there a workaround for this?

like image 349
Jackie Avatar asked Mar 05 '09 18:03

Jackie


2 Answers

http://docs.jquery.com/Events/load

$("#image1").load(function () {
$("#image1").anims();
});
like image 138
Thomas Stock Avatar answered Oct 19 '22 13:10

Thomas Stock


You could preload the image

var oImage = new Image();

oImage.onload = function(){
    this.width// width of loaded image
}

oImage.src = '/path/to/image.gif';

$(document).ready won't wait for images to load, it waits for the dom to be ready.

like image 3
Simon Avatar answered Oct 19 '22 14:10

Simon