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,233
  • 11
  • 55
  • 86
  • First that came to a head. You can create DOM-element `img` set `display: none` and `src` of your image. After image loaded you can get it's real dimensions – d.k Aug 01 '12 at 18:30
  • thanks for advice but it must be done with this way, – Barlas Apaydin Aug 01 '12 at 18:32

3 Answers3

5

Try this:

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

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

Esailija
  • 138,174
  • 23
  • 272
  • 326
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,941
  • 4
  • 54
  • 75
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
  • 70,514
  • 10
  • 99
  • 103