I am trying to implement a 'toggle visibility with sliding motion' functionality like jQuery's slideDown() in plain JS.
I can animate values over time, no problem, but what do I do when the height of the element that should become visible is unknown?
Existing sample solutions always seem to animate the max-height value up to a fixed value, but I need to animate to previously unknown value (height).
(If there's a way to achieve this with css3, I would also be curious!)
Set the height of your element to 0, with hidden overflow, and a CSS3 transition to handle the animation:
.container {
height: 0px;
overflow: hidden;
transition: all 1000ms;
}
You can then easily animate the element based on its scrollHeight
:
var container= document.querySelector('.container');
container.style.height= container.scrollHeight + 'px';
Snippet
document.querySelector('button').addEventListener('click', function() {
var container= document.querySelector('.container');
container.style.height= container.scrollHeight + 'px';
});
.container {
font: 24px verdana;
background: #dfd;
height: 0px;
overflow: hidden;
transition: all 1000ms;
}
<button>
Slide Down
</button>
<div class="container">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With