Reputation: 7309
I am new to jquery.. I'm having to animate a div to a certain height.. And again on the next click, i need to animate it to height auto. I am able to animate only when i provide the height in px.. here is my code.. can any1 suggest how to find the height of the div on page load.
$("#photobutton").click(function(){
var $text = $("#photobutton").text();
if($text == "hide photos")
{
$("#photocontainer").animate({height: '144px'}, 1000);
$("#photobutton").text("more photos");
}
else if($text == "more photos")
{
$("#photocontainer").animate({height: '100%'}, 1000);
$("#photobutton").text("hide photos");
}
});
on the if condition i want the div to collapse to height144px.. and in the else conditions i want the div to stretch to its full height to display all the elements..
Upvotes: 2
Views: 4163
Reputation: 66673
In your second animate()
call, assuming you want this div to fill the height of its parent, use:
$("#photocontainer").animate({height: $("#photocontainer").parent().height()+'px'}, 1000);
EDIT
Example of animating height to fill parent's height: http://jsfiddle.net/techfoobar/HXjfe/
Example of animating height to fill window's height: http://jsfiddle.net/techfoobar/C37rs/1/
EDIT #2
Animating to auto height: http://jsfiddle.net/techfoobar/psexn/3/
jQuery's animate function will not animate to auto height by itself. In fact, it will not animate to any height that cannot be determined prior to the animation.
We can however get it to do it. But it involves a rather ugly hack. The hack is to hide the div, set height to auto, note the height, revert the height and visibility. Once we have the target height, animate it.
Upvotes: 2
Reputation: 42450
Jquery's animate
method works just fine with percentages as well as pixels.
Here's an example: http://jsfiddle.net/KH8Gf/11/
This leads me to believe the issue is that you haven't properly defined a parent for the div photocontainer
. When you state a height in percentage, it means, x% of the parent. If a parent is not defined, it won't work with percentages.
Post your HTML markup and CSS if possible.
UPDATE
When you're animating the exapndsion of photocontainer, you have to specify to what height it should expand. To do this, you need to know the height you want, either in percentage or pixels.
If you want photocontainer
to be able to hold a variable amount of data, you need to change your strategy. Define photocontainer
to have height auto
, and then when expand is clicked, add the new elements inside photocontainer
. Photocontainer
will automatically expand to an appropriate size.
See example: http://jsfiddle.net/KH8Gf/21/
Upvotes: 1
Reputation: 20431
You'll want to work with pixels, not percents.
$(window).height(); // returns height of browser viewport
$(document).height(); // returns height of HTML document
Retrive the relevant one, and use .height();
to set it.
Upvotes: 2