user1434702
user1434702

Reputation: 829

Get dimensions of an IMG dynamically in load event

Dimension of the 11.jpg is not 100*100, but I want to get real dimension of the image in load event. How could I do it?

<img id="t" src="img/11.jpg" width="100px" height="100px" />

$('#t').load(function() {

});

Upvotes: 1

Views: 83

Answers (2)

Umesh Aawte
Umesh Aawte

Reputation: 4690

Using jQuery,

$(document).ready(function() {
    alert("Widht :" + $("#t").width() + "\nHeight :" + $("#t").height());    
});​

Using plain javaScript

var imgObj = document.getElementById("t");
 alert("Widht :" + imgObj.width + "\nHeight :" + imgObj.height);  

Please remove height and width if you want to use jQuery way. Your html should be,

<img id="t" src="http://www.gravatar.com/avatar/8953449b7b29d04cb89adaf912d84980?s=32&d=identicon&r=PG" />

Try this working example here

Upvotes: 0

Jared Farrish
Jared Farrish

Reputation: 49188

I don't necessarily know that this is the best way, or if you need the inner img.onload per se, but you could use an Image object to get the img without the width and height attributes.

$('#t').load(function() {
    var img = new Image();
    img.src = this.src;

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

Demo (have your console open): http://jsfiddle.net/ZgKGG/1/ Note, the attributes on the img tag give it 100x100 dimensions, but the image is actually 128x128.

Upvotes: 1

Related Questions