1

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,

Barlas Apaydin
  • 7,125
  • 11
  • 54
  • 84

3 Answers3

5

Try this:

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

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

Esailija
  • 134,577
  • 23
  • 263
  • 318
0
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;}​
Purag
  • 16,611
  • 4
  • 51
  • 72
0

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.

Mike Brant
  • 68,891
  • 9
  • 93
  • 99