1

If i had an image with a url such as img/160x180.jpg how using this alone in jquery/javascript can i get the width and height of it. i have tried

alert($('<img src="img/160x180.jpg"/>').naturalWidth)

in the example below it returns undefined.

http://jsfiddle.net/D7dx6/

Yusaf Khaliq
  • 3,333
  • 11
  • 42
  • 82

2 Answers2

4

Updated:

alert($('<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif"/>')[0].width);

edit — that doesn't really make sense; it needs to be in an event handler:

$('<img/>', {
  'load': function() { alert(this.width); },
  'src': 'http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif'
});

That code, it should be noted, might have problems on IE because it sometimes drops the ball if the "src" is set and the image is found in cache before the "load" handler is established. In that case, you can do this:

$('<img/>', { 'load': function() { alert(this.width); } }).prop('src', 'http://...');

There's no "naturalWidth" property.

Though it's pretty much irrelevant overhead in this case, you can do this without jQuery like this:

var img = new Image();
img.onload = function() {
  alert(img.width);
};
img.src = "http://placekitten.com/300/400";

Now one thing to watch out for is that if you're looking at actual page elements (that is, <img> tags on the page), they might have "width" attributes that override the true size. Fetching the image again will generally pull it out of cache, though there's some potential pain there for huge images on mobile devices.

(edit — Graham points out that there is a "naturalWidth", but it's not well-supported at this time.)

Pointy
  • 405,095
  • 59
  • 585
  • 614
2

naturalWidth and naturalHeight aren't well supported yet: see https://developer.mozilla.org/en/DOM/HTMLImageElement.

The pure-JavaScript way to determine the original dimensions of an image, whether or not it currently exists in the DOM, is to use the Image object.

var img = new Image();
img.src = 'path/to/img.jpg';
// you'll probably want to use setTimeout to wait until the imh.complete is true
console.log(img.width);
Graham
  • 6,484
  • 2
  • 35
  • 39