I’ve got a function to detect the size of an image, and I want it to return an object that contains both the width and height. In the code below, sz.width and sz.height within the function hold the values, but after they return the value it’s undefined. What am I missing?
function getImgSize(imgSrc) {
var newImg = new Image();
newImg.onload = function() {
var height = newImg.height;
var width = newImg.width;
function s() {}
sz = new s();
sz.width = width;
sz.height = height;
$('#infunc').text("in function, w = "+sz.width+", h = "+sz.height);
return sz;
}
newImg.src = imgSrc; // this must be done AFTER setting onload
}
var sz = getImgSize("http://lorempixel.com/output/fashion-q-c-1920-1920-4.jpg");
$('#outfunc').text("outside function, w = "+sz.width+", h = "+sz.height);
jsfiddle: http://jsfiddle.net/forgetcolor/LbxA3/
The function
getImgSizesets up the image loading and then terminates. Later, when the image loads, the anonymous onload function is invoked and correctly calculates the size, then returns it, to an uncaring DOM engine…You’re probably wondering how you can do what you want. Short answer: you can’t. Here’s the closest you can get:
I actually came here to write:
That’s what I bet your problem was.
// this must be done AFTER setting onload