JavaScript slidedown without jQuery

Since we are in 2014, why not use CSS transitions and just change the height property of the element?
Fiddle

CSS:

.wrapper {
    transition:height 1s ease-out;
    height:0;
    overflow:hidden;
}

HTML:

<div id="wrapper">
//content
</div>

JAVASCRIPT:

document.getElementById("wrapper").style.height = //content height +"px";

2020 EDIT (dealing with unknown height):

So we’re in 2020 and it’s even more obvious now we should rely on CSS effects for this kind of animations.

However, a valid point has been made against this answer – you need to specify the height of the element that you’re animating in the js code, and you might not know this value in advance.

So six years later, I’m adding a couple extra lines of code to cover this case.

So if we use the same CSS and HTML as in our old 2014 example, this is the new JS.
New Fiddle!

const slideDown = elem => elem.style.height = `${elem.scrollHeight}px`;

slideDown(document.getElementById("wrapper"));

Leave a Comment