1

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.

Control Freak
  • 12,965
  • 30
  • 94
  • 145

4 Answers4

6

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;
Trevor
  • 9,518
  • 2
  • 25
  • 26
2

Try

img.onload = function(){alert(img.width);}

instead of

img.onLoad = alert(img.width);
  • +1 This is the correct answer. The original code was executing the `alert()` statement immediately and assigning its return value to `img.onload` which will obviously not do what was intended. – jfriend00 Jun 19 '12 at 05:29
0
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?

Community
  • 1
  • 1
sandeep patel
  • 436
  • 4
  • 16
-1

Use the clientWidth property of the image element.

img.clientWidth;
C0deH4cker
  • 3,959
  • 1
  • 24
  • 35