Folding a <div>
I made this code originally for the navigation menu (of the mobile layout) on this site. It shows you how to show/hide a <div> (that's contained in another one). The original code makes use of the animation package on pub, so that code is commented out there if you want to use it. animation is used to make the folding smooth and not instant.
The HTML & CSS
We have the fold area contained inside of a <div> with the id of
foldable and has the class
header section contains two
spans, one being the
title and the other being the
button. Most of the CSS is just for making this look pretty the but the
overflow: hidden property for
content is important so the text doesn't bleed past the <div>.
main() function we grab the two important divs
#foldable .content and
#foldable .button using querySelector(), then we add a listener for click events on the
_closeOrOpen() is the most important function since it's what actually will hide/show the
toggleFold() we toggle the boolean
divOpen and then call the function
For a smoother transition (using the animation package), we grab the size of the
#foldable .content region before doing anything. We want the animation to close the
content area in about a 1/3 of a second. We setup the
properties map to change the height to either
0px or the original size, and set it in motion using the
animate() function. Right after that too, we have to call
_closeOrOpen() as well, but after the animation is done.