Skip to content

Instantly share code, notes, and snippets.

@Asikur22
Created November 1, 2021 11:16
Show Gist options
  • Save Asikur22/f6c75427f3dabf3cd79453e32b605c15 to your computer and use it in GitHub Desktop.
Save Asikur22/f6c75427f3dabf3cd79453e32b605c15 to your computer and use it in GitHub Desktop.
Vanilla JS Slide Up/Down
var mainMenu = document.querySelector( '#menu-primary-navigation' );
document.querySelector( '.mainMenuToggler' ).addEventListener( 'click', function ( event ) {
event.preventDefault();
/** Slide down. */
if ( !mainMenu.classList.contains( 'active' ) ) {
/** Show the mainMenu. */
mainMenu.classList.add( 'active' );
mainMenu.style.height = "auto";
/** Get the computed height of the mainMenu. */
var height = mainMenu.clientHeight + "px";
/** Set the height of the content as 0px, */
/** so we can trigger the slide down animation. */
mainMenu.style.height = "0px";
/** Do this after the 0px has applied. */
/** It's like a delay or something. MAGIC! */
setTimeout( () => {
mainMenu.style.height = height;
}, 0 )
/** Slide up. */
} else {
/** Set the height as 0px to trigger the slide up animation. */
mainMenu.style.height = "0px";
/** Remove the `active` class when the animation ends. */
mainMenu.addEventListener( 'transitionend', () => {
mainMenu.classList.remove( 'active' );
}, {once: true} );
}
} );
#menu-primary-navigation {
transition: height .5s ease;
overflow : hidden;
}
#menu-primary-navigation:not(.active) {
display: none;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment