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]);

3 Answers 3

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 !

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

2 Comments

I won't argue that it's bad code, but your suggestion doesn't work. x and y are still undefined using your method.
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
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);
};

1 Comment

I tweaked it, but your solution of calling a function from within the load function worked. Thanks.
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);

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.