views:

765

answers:

4

I'm writing a jQuery function where I'd like to access both the native size of an image, and the size specified for it on the page. I'd like to set a variable for each.

How is that done?

A: 

EDIT - new idea... see http://jsbin.com/uzoza

  var fixedW = $("#imageToTest").width(); 
  $("#imageToTest").removeAttr("width"); 
  var realW = $("#imageToTest").width(); 
  $("#imageToTest").attr("width", fixedW);

ORIGINAL ANSWER

see http://stackoverflow.com/questions/623172/how-to-get-image-size-height-width-using-javascript

var img = $('#imageid'); 

var width = img.clientWidth;
var height = img.clientHeight;
Josh
that won't give you the native width
I.devries
is it possible to remove the size attributes with jQuery take the size and then reapply them?
Josh
What happens if the width is defined by using css? And: Doesn't this mess with the layout?
Georg
you can remove the css width in the same way see http://jsbin.com/ulude
Josh
+1  A: 

My solution would be to write a web service that gets/downloads the image, and then gets its resolution and returns it as {width: x,height:y}. Then you call it with $.ajax or equivalent to retrieve this.

Alternatively you could add the image to a hidden div using

// e.g. don't set width and height
$("#hiddendiv").html("<img src='theurl'>");

And then get the div's width/height though I haven't tried it.

Chris S
If I recall correctly, you can't get width/height on hidden elements. (they will return 0)
TM
+7  A: 
// find the element
var img = $('#imageid');

/* 
 * create an offscreen image that isn't scaled
 * but contains the same image.
 * Because it's cached it should be instantly here.
 */

var theImage = new Image();
theImage.src = img.attr("src");

// you should check here if the image has finished loading
// this can be done with theImage.complete

alert("Width: " + theImage.width);
alert("Height: " + theImage.height);
Georg
I was hoping there was just an image property I had missed, but this is a good workaround. Thank you.
Nathan Long
Nice, I just used this
rado
+1  A: 

This should work:

var img = $('#imageid')[0]; //same as document.getElementById('imageid');
var width = img.naturalWidth;
var height = img.naturalHeight;

The naturalWidth and naturalHeight return the size of the image response, not the display size.

According to Josh' comment this is not supported cross browser, this might be correct, I tested this in FF3

Pim Jager
-1 not supported cross browser unfortunately!
Josh
I wouldn't use this if it's not cross-browser, but it's still interesting to know about. Thanks!
Nathan Long