user1357182
user1357182

Reputation: 59

How do I get javascript to return this value?

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);

Upvotes: 0

Views: 192

Answers (3)

t0yv0
t0yv0

Reputation: 4724

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).

Upvotes: 0

Sirko
Sirko

Reputation: 74036

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.

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227200

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.

Upvotes: 3

Related Questions