0

Possible Duplicate:
Javascript - Function to return width/height of remote image from url

Is it possible to get width and height by just knowing the images location with js? The actual picture isn't loaded onto the DOM. I have been trying this with jQuery but with no luck yet.

var img = $('<img>').attr('src', 'images/logo.png');
console.log($(img).width());

returns 0.

Community
  • 1
  • 1
Philip
  • 6,827
  • 13
  • 75
  • 104

3 Answers3

2

No, the image doesn't need to be in the DOM.

var img = new Image();
img.onload = function(){
        console.log(this.width);
    };
img.src="images/logo.png";

But you have to load it before knowing its dimensions

(note the src after the onload function)

here is a jsfiddle : http://jsfiddle.net/fGUyz/2/

#NotMrDownVoter

nicolast
  • 787
  • 7
  • 20
1

Unfortunately the image must be in the DOM for the width/height to be calculated.

You can cheat this by appending it to the page, but positioning it well off the screen, like this:

.offscreen {
    position: absolute;
    left: -9999px;
}
var $img = $('<img>', {
    'src': 'images/logo.png',
    'class': 'offscreen'
}).appendTo('body');
console.log($img.width());
$img.remove() // if required...
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Also, wrap this logic inside [`load`](http://api.jquery.com/load-event/) instead of `ready`; this makes sure that the images have been loaded in the first place so it can measure them. Demo here: http://api.jquery.com/load-event/#entry-examples #NotMrDownVoter – Ayman Safadi Feb 03 '13 at 17:19
  • Actually, @Dr.Molle pointed me into the right direction, – Philip Feb 03 '13 at 17:24
0

Unfortunately as Rory McCrossan has already suggested, when using JQuery you must add the element to the DOM before any of the width() or height() functions will return anything other than 0.

Having a hidden element will also return width/height of 0.

Jamie
  • 876
  • 1
  • 10
  • 28