I want to implement a dropdown menu for mobile devices with animation so when the transition ends, it needs to be display:none. Here’s what I’ve done:
const menuButton = document.querySelector('.menuButton')
const navMenu = document.querySelector('.nav')
function menuToggle() {
if (navMenu.classList.contains('navDisplay')) {
navMenu.classList.remove('navShow')
setTimeout(() => {
navMenu.classList.remove('navDisplay')
}, 300)
} else {
navMenu.classList.add('navDisplay')
setTimeout(() => {
navMenu.classList.add('navShow')
}, 0)
}
}
menuButton.addEventListener('click', menuToggle)
* {
margin: 0;
padding: 0;
-webkit-font-smoothing: antialiased;
color: #e8e8e8;
}
html, body {
overflow-x: hidden;
background-color: rgb(66, 66, 66);
}
h2 {
margin: 15px 0;
}
a {
transition: all.3s ease;
-webkit-transition: all.3s ease;
-moz-transition: all.3s ease;
color: #e8e8e8;
text-decoration: none;
}
a:hover {
color: #777777;
}
/*--------------NAV BAR------------*/
header {
background-color: rgba(24, 24, 24, 0.95);
position: fixed;
width: 100%;
top: 0;
z-index: 10;
}
.menuButton {
display: none;
position: fixed;
right: 0;
color: white;
font-size: 1.5em;
line-height: 65px;
margin: 10 30px;
user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
cursor: pointer;
}
.logo {
color: white;
font-size: 30px;
font-weight: bold;
font-family: 'Fredoka One', sans-serif;
line-height: 65px;
}
nav div ul {
text-align: center;
flex-direction: column;
margin-top: 50px;
overflow: hidden;
}
nav div ul li {
margin: 20px 0;
}
nav {
flex-direction: column;
}
.nav {
display: none;
box-sizing: border-box;
width: 100%;
overflow: hidden;
height: 0;
transition: height 300ms ease-in-out;
-webkit-transition: height 300ms ease-in-out;
-moz-transition: height 300ms ease-in-out;
}
.orderButton {
padding: 20px;
}
.logo {
text-align: center;
}
.menuButton {
display: block;
}
.navShow {
height: 100vh;
}
.navDisplay {
display: block;
}
<header>
<div class="menuButton">☰</div>
<nav>
<a href="index.html"><p class="logo">LOGO</p></a>
<div class="nav">
<ul>
<li><div class="orderButton">ELEMENT1</div></li>
<li><a href="about.html">ELEMENT2</a></li>
<li><a href="contact.html">ELM3</a></li>
</ul>
</div>
</nav>
</header>
So, the menu is display:none and height:0 by default. The click event listener triggers function that checks if menu is displayed or not and adds or removes respective classes (the display class removes after the transition ends with the help of timeout 400ms).
Is there any more beautiful or less code solutions?