Getting Value of Image Width from JavaScript Image Onload Function

tech-otaku :

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.

Łukasz Nojek :

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:

  1. 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"
    
  2. 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);
    }
    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31944&siteId=1