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?
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?
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;
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.
// 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