0

I have this code in jquery:

var ratio;
$("<img/>").attr("src", $(img).attr("src")).load(function() {
ratio = this.width / this.height;
    alert(ratio);
});

This retuns the correct ratio, but when I try this

var ratio;
$("<img/>").attr("src", $(img).attr("src")).load(function() {
ratio = this.width / this.height;        
});
alert(ratio);

It returns undefined.

I do not understand why this happens even though I have declared globally the ratio variable.

I use this in the following exemple:

working http://jsfiddle.net/7sUAY/5/

not working http://jsfiddle.net/7sUAY/6/

Thank you, Mugur

1
  • 1
    Because the load callback is executed only when the image was loaded, whereas every code following $("<img/>").attr().load() is executed immediately. Otherwise, what would be the reason to provide a callback at all? Commented Feb 9, 2012 at 11:34

2 Answers 2

2

You only assign a value to ratio inside a callback (passed to the load function). This callback will be made when the image has loaded. It will not have been made before the point where ratio is alerted and so ratio remains undefined.

See here for the load method documentation.

Sign up to request clarification or add additional context in comments.

Comments

2

That's because the .load() method takes more time. Your alert is executed faster than the image has been loaded.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.