How can I access the value of imgWidth? This is giving me undefined.
somejQueryMethod(function() {
var imgWidth;
$("<img/>").attr(
"src",
$("#SomeImgSelector").attr("src")
).load(function() {
imgWidth = this.width;
});
// use imgWidth here
// imgWidth is undefined here
});
Background info: From this SO question I assumed that as
imgWidthwas being defined outside of theload()method,
it would always be available outside ofload(). Which makes me
wonder why defineimageWidththere and not inload()?
You can’t use the value there, because it doesn’t exist yet. The callback function in the
loadcommand runs after the content has been loaded, and that happens after the function using theloadcommand ends.Put the code that needs the value inside the callback function for the
loadcommand: