0

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]);
Community
  • 1
  • 1
Brandon Lebedev
  • 2,717
  • 6
  • 24
  • 35

3 Answers3

1

imagepopXY contains the image and not the function !

So you can't call it like this.

If you want to define global variables, define them before the function :

var x; var y;

var imagepopXY = $("<img/>").attr('src', imagepopSrc).load( function() {
    x = this.width;
    y = this.height;
});

but this is not a very good code !

Jerome Cance
  • 8,103
  • 12
  • 53
  • 106
  • I won't argue that it's bad code, but your suggestion doesn't work. `x` and `y` are still undefined using your method. – Brandon Lebedev Aug 09 '11 at 17:54
  • you must take care that the load method is called asynchronous. So if you test x and y just after the imagepopXY assignment, x and y will be undefined ! X and Y will only be filled when the image is loaded – Jerome Cance Aug 09 '11 at 18:00
0

Try it like this:

var imagepopXY = {};

$("<img/>").attr('src', imagepopSrc).load( function() {
    imagepopXY.x = this.width;
    imagepopXY.y = this.height;

});

alert ('X: ' + imagepopXY.x + ' Y: ' + imagepopXY.y);
Mrchief
  • 75,126
  • 20
  • 142
  • 189
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:

$("<img/>").attr('src', imagepopSrc).load(function() {
  keepWorkingWithTheImage(this.width, this.height);
});

var keepWorkingWithTheImage = function(x, y) {
 // your code is here
 alert(x);
 alert(y);
};