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?
When I wrote this answer back in 2009 the browser landscape was much different. Nowadays any reasonably modern browser supports Pim Jager's suggestion using img.naturalWidth
and img.naturalHeight
. Have a look at his answer.
// 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);
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
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 How to get image size (height & width) using JavaScript?
var img = $('#imageid');
var width = img.clientWidth;
var height = img.clientHeight;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With