I have the following which gets the width of a given image:
<!DOCTYPE html>
<html>
<head>
<title>Image Width</title>
<script>
var img = new Image();
img.onload = function() {
alert("Width: " + img.width);
};
img.src="http://www.hq.nasa.gov/office/pao/History/alsj/misc/apmisc-60-SAT-1.jpg"
// Do something with 'img.width' here, outside the image onload event handler.
</script>
</head>
<body>
</body>
</html>
I understand that I need the image to load before getting its width, and how to get its width from within the image onload event handler, but I'm having real difficulty accessing its width from outside the handler.
Am I just being an idiot and missing something really simple or is it more complex than I think?
Any help would be most appreciated.
Regards, Steve.
The problem you face is asynchronous programming. The onload
function will be called by the engine at a later time, and the program will hold its execution.
There are two options:
If you need the value as soon as possible, you'll have to run the code inside
onload
, e.g.:var img = new Image(); img.onload = function() { alert("Width: " + img.width); // Do something with 'img.width' here, outside the image onload event handler. }; img.src="http://www.hq.nasa.gov/office/pao/History/alsj/misc/apmisc-60-SAT-1.jpg"
If the code that will access
img.width
will happen later, e.g. after user clicks something, you can store the value and use it elsewhere:var width; var img = new Image(); img.onload = function() { width = img.width; }; img.src="http://www.hq.nasa.gov/office/pao/History/alsj/misc/apmisc-60-SAT-1.jpg" function anotherFunction() { alert(width); }