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.>
I'm adding a way to accomplish this and be sure that there is support for all browsers. Pretty much all browsers support naturalWidth and naturalHeight except for Internet Explorer 8 and below.
Since IE 8 and below would return the size of the visible image and not the natural size when using trying to retrieve size values, a small workaround is needed to get the full size dimensions which came from an example by Jack Moore.
function naturalSize(imageid) {
imageid = (imageid.src ? imageid : document.getElementById(imageid));
if (document.documentMode < 9) {
var img = new Image();
img.src = imageid.src;
return {width: img.width,height: img.height};
}
return {width: imageid.naturalWidth,height: imageid.naturalHeight};
}
I set this up to support passing either the image ID value or the name of the ID.
Usage:
naturalSize("some_img");
// Returns: Object {width: 731, height: 387}
Or
// Displays: Size: 731x387
Be sure to make sure the image is loaded before calling this, whether by using onload or triggering upon adding it to the DOM.
Tested with: Windows XP - Firefox 1.5, IE 8 Windows 7 - IE 9, Chrome 56 Android 6.0.1 - Chrome 50 Android 5.1.1 - Opera Mini 7.6, Dolphin 10.3
Full code example: