I want to animate a <div>
from 200px
to auto
height. I can’t seem to make it work though. Does anyone know how?
Here’s the code:
$("div:first").click(function(){
$("#first").animate({
height: "auto"
}, 1000 );
});
I want to animate a <div>
from 200px
to auto
height. I can’t seem to make it work though. Does anyone know how?
Here’s the code:
$("div:first").click(function(){
$("#first").animate({
height: "auto"
}, 1000 );
});
You can always wrap the child elements of #first and save height height of the wrapper as a variable. This might not be the prettiest or most efficient answer, but it does the trick.
Here's a fiddle where I included a reset.
but for your purposes, here's the meat & potatoes:
I managed to fix it :D heres the code.
I needed this functionality for multiple read more area's on one page implementing this into a Wordpress shortcode I ran into the same problem.
Design technically all of the read more span's on the page have a fixed height. And I wanted to be able to expand them separately to an auto height with a toggle. First click: 'expand to full height of text span', second click: 'collapse back to default height of 70px'
Html
CSS
So above this looks very simple the
data-base
attribute I need to set the fixed height needed. Thedata-height
attribute I used to store the actual (dynamic) height of the element.The jQuery part
First I've used a clickToggle function for my first and second click. The second function is more important:
setAttr_height()
All of the.read-more
elements have their actual heights set on page load in thebase-height
attribute. After that the base height is set through the jquery css function.With both of our attributes set we now can toggle between them in a smooth way. Only chang the
data-base
to your desired (fixed)height and switch the .read-more class for your own IDYou can all see it working in a fiddle FIDDLE
A better solution would not rely on JS to set the height of your element. The following is a solution that animates a fixed height element to full ("auto") height:
https://gist.github.com/2023150
Basically the height auto is only available for you after the element is rendered. If you set a fixed height, or if your element is not displayed you can't access it without any tricks.
Luckily there are some tricks you may use.
Clone the element, display it outside of the view give it height auto and you can take it from the clone and use it later for the main element. I use this function and seems to work well.
USAGE:
This is basically the same approach as the answer by Box9 but I wrapped it in a nice jquery plugin that takes the same arguments as a regular animate, for when you need to have more animated parameters and get tired of repeating the same code over and over:
edit: chainable and cleaner now