views:

5791

answers:

7

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?

A: 

You could use a setTimeout() function to delay the execution long enough for the image to load.

Here is an example of how it works:

setTimeout("alert('hello world');", 5000);

The first argument is a string that your javascript engine will parse as executing code and the second argument is an integer value that represents how many milliseconds you wish to delay before the code in your first argument executes.

Andrew Hare
Will the amount of milliseconds necessary change depending on computer/internet connection speed? Ideally it would be ready ASAP, so I wouldn't want to delay it by ten seconds or anything, but I also wouldn't want to leave slowpokes in the dark.
Jackie
A: 

I believe you can use

$(this).ready()
{
    // stuff with $(this).width() in here
}

I do not think .ready() is exclusive to the document.

Logan Serman
A: 

By the time $(document).ready is called, the image should already have been loaded. Something else is wrong.

If you need to know the width of the image before you start the animation, but the image needs to be in some form of hidden state when the animation starts, you could capture the image width width .width() before the animation, and call .hide() or whatever else is appropriate, immediately after measuring the width.

Jaanus
$(document).ready only guarantees the DOM is ready, not assets (like stylesheets, images or other JavaScripts).
thenduks
+3  A: 

The solution on SO.

ybo
A: 

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.

Simon
+2  A: 

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

$("#image1").load(function () {
$("#image1").anims();
});
Thomas Stock
A: 

Do a fadeIn before reading any dimensions:

$('#image').fadeIn(10,function () { var tmpW = $(this).width(); var tmpH = $(this).height(); });

Dio