marcamillion
marcamillion

Reputation: 33755

How do I detect height of an image in jQuery?

I tried the following code:

    var origh1 = $('img:first').height();
    alert(origh1);

But it alerted a value of '0'.

My img tag does not have a height value set, so is that why it is returning 0?

If so, how do I retrieve the value of the height of the image ?

Also, I noticed that when I do an animate to increase the size of the image by 20% and reduce it 20%, it ends up being a little larger than the original. How do I restore the image to it's original size? And why does it not go back to original if I reduce it 20%. I know that there is Math involved...but how do I compensate for that in jQuery?

This is my code for that:

$('img:first').fadeIn('normal').delay(500).animate({'height':'+=20%'}, 1500, 'easeOutQuad')

And the return to original:

$('img:first').fadeIn('normal').animate({'height':'-=20%'}, 1000, 'swing');

Upvotes: 3

Views: 109

Answers (2)

Greg
Greg

Reputation: 7922

Try

$(window).load(function(){
    $('img:first').attr("height")
});

This will fire after your images have fully loaded

edit -- Sorry, I had to edit that about five times. I keep making silly mistakes today.

Upvotes: 2

meder omuraliev
meder omuraliev

Reputation: 186562

Make sure the image properly loads before you query it.

$(function() {
     alert( $('img').eq(0).height() )
});

You can also try binding it to the window load event if DOM Ready is too soon:

$(window).load(function() {
     alert( $('img').eq(0).height() )
});

Upvotes: 2

Related Questions