David Hellsing
David Hellsing

Reputation: 108500

Detecting image width via JavaScript when maxWidth is used

Consider this code:

var img = new Image();

img.onload = function() {
    console.log(this.width);
};

img.src = 'http://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Gull_portrait_ca_usa.jpg/800px-Gull_portrait_ca_usa.jpg';

document.body.appendChild(img);

This will print out the image width (800) correctly. But if I apply a max-width using CSS:

img {max-width: 400px}

Test case: http://jsfiddle.net/MSjnM/

The JS code above will print out 400 instead. That is a bit confusing, as one would think that the width attribute represents the original image width, not the computed width.

Now to something even more confusing, if I append the image in the onload event after the width detection I get a different result:

var img = new Image();

img.onload = function() {
    console.log(this.width);
    document.body.appendChild(img);
};

img.src = 'http://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Gull_portrait_ca_usa.jpg/800px-Gull_portrait_ca_usa.jpg';

Test case: http://jsfiddle.net/MSjnM/2/

This will print out 800 instead, even though the CSS has applied. I assume it’s because the image is appended after I detected the width and that the max-width will be applied as soon as the image is inserted into the DOM.

OK, so if I want to get the original image size, no matter when or if the IMG element is inserted in the DOM or whatever CSS styles has been applied, how would I do that fail-safe?

Upvotes: 0

Views: 753

Answers (2)

Dr.Molle
Dr.Molle

Reputation: 117354

For me: in IE9, Opera, Safari(PC), FF and chrome the naturalWidth/naturalHeight-properties return the desired values

http://jsfiddle.net/MSjnM/5/

Upvotes: 2

Baxter
Baxter

Reputation: 2456

Load the image independently into a new Image object and get the width there:

var img = new Image();
img.src = 'http://placehold.it/350x150'
console.log(img.width);

Upvotes: 2

Related Questions