bob_cobb
bob_cobb

Reputation: 2269

Accessing properties from within a callback

I'm loading in an image into memory per a solution I found on here, and that's fine, but since it's within a callback, the properties width and height are undefined outside of it.

var originalWidth, originalHeight;
$("<img/>") // Make in memory copy of image to avoid css issues
    .attr("src", $(img).attr("src"))
    .load(function() {
        originalWidth = this.width;   // Note: $(this).width() will not
        originalHeight = this.height; // work for in memory images.
    });
console.log(originalWidth); // undefined obviously since `this` is only accessible within `load`s callback. 

I thought about maybe putting it within an object like:

var originalWidth, originalHeight;
var imgDimensions = {};
$("<img/>") // Make in memory copy of image to avoid css issues
    .attr("src", $(img).attr("src"))
    .load(function() {
        imgDimensions.originalWidth = this.width;   // Note: $(this).width() will not
        imgDimensions.originalHeight = this.height; // work for in memory images.
    });
console.log(imgDimensions['originalWidth']); // undefined also

How can I return those properties from within load()?

Upvotes: 0

Views: 61

Answers (3)

slashingweapon
slashingweapon

Reputation: 11307

If you call console.log() from within the callback, you should get a useful result:

var originalWidth, originalHeight;
var imgDimensions = {};
$("<img/>") // Make in memory copy of image to avoid css issues
    .attr("src", $(img).attr("src"))
    .load(function() {
        imgDimensions.originalWidth = this.width;   // Note: $(this).width() will not
        imgDimensions.originalHeight = this.height; // work for in memory images.
        console.log(imgDimensions);
    });

As others have explained, the .load() callback gets executed at some unspecified time in the future. There's no point in trying to use the imgDimensions variable until then.

Upvotes: 0

Rob Raisch
Rob Raisch

Reputation: 17357

Since you do not know nor can you control when the callback will run, you cannot guarantee that the value will be available for your call to log.

Depending on what you want to do with the dimensions, one solution might be to add an onload event handler to your img tag so you can access the values once the item has actually been loaded.

Upvotes: 1

Musa
Musa

Reputation: 97672

The console.log is executing before the load function fires, therefore originalWidth is not updated as yet.

Upvotes: 2

Related Questions