0

The alert works, but the return is 0. How do I get it to return the correct value?

var img;
img = new Image();
img.onload = function() {
   alert(img.width);
   return(img.width);
};
img.src = "https://maps.gstatic.com/mapfiles/dir/bike.png";
alert(img.width);
3
  • 1
    onload will be executed at an arbitrary point in the future: do what you need to do in the onload function itself. Commented Jun 7, 2012 at 15:41
  • Maybe you should explain what you are actually trying to accomplish. Then somebody might be able to give you a way to get there. Commented Jun 7, 2012 at 15:58
  • Where are you trying to return img.width to? The more information you give, the better you can be helped. Commented Jun 7, 2012 at 21:31

3 Answers 3

3

You can't do that. onload runs once the image is loaded, which means after setting the src, onload will run later.

You need to put all code dealing with the image's width inside the onload.

Sign up to request clarification or add additional context in comments.

Comments

2

You can return the value, but you have no way of capturing it.

The function you pass to onload is executed, when your image has loaded. But there is no way to retrieve the return value there. You can just call another function inside, to process the value.

2 Comments

Ok, so there is no way to return that value?
@user1357182 Just by calling another function and passing it on as a parameter. That's the nature of asynchronous coding.
0

I get 10 from this code in Chrome:

var img = new Image();
img.onload = function() { console.log(img.width); }
img.src = "https://maps.gstatic.com/mapfiles/dir/bike.png";

You do have to wait for the image to load before querying width (in onload).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.