Reputation: 13233
I am getting the image size using javascript, but it won't return the correct size until after I run it a second time. I wonder why this is. Here is my code:
var img = new Image()
img.src = src
img.onLoad = alert(img.width);
This returns 0
sometimes, but after a couple times it returns the actual image width. How do I make it get the right size the first time? I thought this was the right way.
Upvotes: 1
Views: 387
Reputation: 9578
The problem is you are calling alert directly instead of assigning it as a callback so it is called before the image is loaded. This is what you want to do:
var img = new Image();
img.onload = function() {
alert(img.width);
};
img.src = src;
Upvotes: 6
Reputation: 436
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
found the code from this link:-
How to get image size (height & width) using JavaScript?
Upvotes: 0
Reputation:
Try
img.onload = function(){alert(img.width);}
instead of
img.onLoad = alert(img.width);
Upvotes: 2
Reputation: 4065
Use the clientWidth property of the image element.
img.clientWidth;
Upvotes: -1