Is there any way to read out the "naturalWidth" of an image with jquery?

I use the native javascript properties after applying jQuery and then stripping jQuery

.naturalWidth / .naturalHeight

On a jQuery object i use

var width = this.naturalWidth; 
var height = this.naturalHeight;

or

var width = $("selector").get(0).naturalWidth; 
var height = $("selector").get(0).naturalHeight;

if no jQuery object is selected.

With get(0) on a jQuery object you can access the associated DOM-element. On the native DOM element you can work with native javascript code (here access the nativ javascript attribute .naturalWidth)


Here is an example of a jQuery function which works on older IE versions even for large images.

/*
 * NaturalWith calculation function. It has to be async, because sometimes(e.g. for IE) it needs to wait for already cached image to load.
 * @param onNaturalWidthDefined callback(img) to be notified when naturalWidth is determined.
 */
jQuery.fn.calculateNaturalWidth = function(onNaturalWidthDefined) {
    var img = this[0];
    var naturalWidth = img.naturalWidth;
    if (naturalWidth) {
        onNaturalWidthDefined(img);
    } else { //No naturalWidth attribute in IE<9 - calculate it manually.
        var newImg = new Image();
        newImg.src = img.src;
        //Wait for image to load
        if (newImg.complete) {
            img.naturalWidth = newImg.width;
            onNaturalWidthDefined(img);
        } else {
            $(newImg).load(function() {img.naturalWidth=newImg.width; onNaturalWidthDefined(img)});
        }
    }
};

Usage is simple:

$(img).calculateNaturalWidth(function(img) { alert(img.naturalWidth)});

It looks to me like the accepted solution modifies the appearance of the object. Occasionally jQuery is a little too helpful and you have to tell it to get out of your way. If you want to use naturalWidth or naturalHeight then just use the one that already exists by converting the jQuery object into a native browser element reference.

var Height = document.getElementById($(this).attr("id")).naturalHeight;

One way to get the dimensions of an image is to dynamically load a copy of the image using javascript and obtain it's dimensions:

// preload the image
var height, width = '';
var img = new Image();
var imgSrc = '/path/to/image.jpg';

$(img).load(function () {
    alert('height: ' + img.height);
    alert('width: ' + img.width);
    // garbage collect img
    delete img;
}).error(function () {
    // image couldnt be loaded
    alert('An error occurred and your image could not be loaded.  Please try again.');
}).attr({ src: imgSrc });

Tags:

Jquery