Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript slidedown without jQuery

Tags:

javascript

I wish to have a similar effect to jQuery slidedown but without using jQuery or any other libary. I know it's "possible" as anything in jQuery can be done in plain JavaScript. Just harder.

I cannot use jQuery as everything has to be written in my own code without any libaries used.

Has anyone done something like this or any effects just using plain JavaScript?

like image 816
Elliott Avatar asked Sep 25 '10 20:09

Elliott


1 Answers

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"));  
like image 70
Ruben Serrate Avatar answered Sep 18 '22 10:09

Ruben Serrate