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
You only assign a value to
ratioinside 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 whereratiois alerted and soratioremains undefined.See here for the load method documentation.