Reputation: 8177
I have expand and collapse animations on a div in an article element.
Based on this fiddle code: csstransitions demo
When the div box is expanded ("div.expandable") I don't want to leave the height hardcoded (locked) to a specific value, and therefore I reset it by removing the height value: el.css("height", "");
when the animation is complete.
I restore the height (back to say 136px) before setting it again to "0" for the collapse/close animation.
There is no collapsing animation back to height: 0
after having reset it. But if I leave the height to 136px after the expand animation then the collapse animation works fine.
If you comment out el.css("height", "");
then the animation works fine.
Does the height
have to always be set to a specific value? If so then there is no height responsiveness when resizing the browser width.
Upvotes: 4
Views: 645
Reputation: 1911
Set max-height (with a height, your text will never use) instead of height:
JS
$(".preface").click(function(){
var el = $(this).parent().find(".expandable");
el.toggleClass("expanded");
});
CSS
.expandable {
transition: max-height 0.5s ease-in-out;
background-color: #f1f1f1;
overflow: hidden;
max-height: 0;
}
.expanded {
max-height: 2000px;
}
Here's a fiddle with your updated code.
.expandable doesn't need style="height: 0"
anymore. Unfortunately this solution messes up your transition-duration, as it calculates the time needed for max-height, not height.
Upvotes: 0
Reputation: 176
Transitioning heights/widths to/from auto in CSS is tricky, which is essentially what you're doing when you remove the height value. There is a trick to get around that which might help you out: it involves cloning the element, setting the height and width to auto, measuring the height of the duplicate element, and then removing it, allowing you to have flexible heights/widths and still animating them. See http://darcyclarke.me/development/fix-jquerys-animate-to-allow-auto-values-2/ for an example.
Upvotes: 1