I’m setting two local variables inside of a jQuery .load(function(){...}) handler, but I can’t find a way to access those variables outside of the handler. I tried removing the var declaration, but that didn’t work. Now I’m trying to use return, but I can’t get it to work either. Instead of alerting a numerical value, Firefox is alerting “[object HTMLImageElement]” when I run the code.
*I can verify that alert(x) works when placed inside the handler/function.
The code below is a modification of Xavi’s solution to reading the actual dimensions of an image.
var imagepopXY = $("<img/>").attr('src', imagepopSrc).load( function() {
var x = this.width;
var y = this.height;
return [x,y]
});
alert (imagepopXY[0]);
imagepopXY will contain the image, as Jerome already pointed out. The bigger problem is that even in Mrchief’s solution the alert won’t show you those values. Why? Because the load event fires when the image is actually loaded and in most cases that will likely be after the alert triggers (since you’re assigning those values in an event, the rest of the code keeps chugging along without any regard for it).
If your application needs the x and y values before it can continue then it would be best to just put a function call inside the load event. Like this: