Barlas Apaydin
Barlas Apaydin

Reputation: 7315

jQuery calculate img's real height / width values which coming from server

I am in a situation that; need to calculate image's original width and heigth values when one of them defined 0 on css. I can't change CSS with jQuery, need to solve like this:

Here is example link.

CSS:

img { width:0px; }​

jQuery:

var imgHeight = $('img').height();
alert(imgHeight);//which returning 0 ofcourse

I hope this is possible with less code, thanks,

Upvotes: 1

Views: 363

Answers (3)

Purag
Purag

Reputation: 17061

var img = $('img'),
    imgHeight = img.css("width","auto").height();
img.css("width","0");
alert(imgHeight);

Here is a fiddle. All we do is temporarily set the height to it's automatic value (which is the image's 100% width), grab the height, and reset the image to width:0;.

EDIT: Since you can't manipulate CSS directly, you can change the class:

var img = $('img'),
    imgHeight = img.addClass("auto").height();
img.removeClass("auto");
alert(imgHeight);​

And the CSS:

img {width:0;}
img.auto {width:auto;}​

Upvotes: 0

Esailija
Esailija

Reputation: 140228

Try this:

var img = $("img")[0];
alert( img.naturalWidth + "x" + img.naturalHeight );

http://jsfiddle.net/mjaA3/50/

Upvotes: 5

Mike Brant
Mike Brant

Reputation: 71384

You could clone the element to a new hidden DOM node (I assume you want to hide it here). Then remove the CSS, then measure the dimensions.

Upvotes: 0

Related Questions