I'm trying to create a simple hamburger icon that triggers a CSS animation on click using pure Javascript (no jQuery). Currently, I have the animation working when adding a class to the hamburger icon, but when I remove the class, the animation abruptly resets without animating. How can I make the animation reverse and smoothly return to its original position?
Here's the code snippet:
var hamburgerMenu = document.querySelector('.hamburger-menu');
hamburgerMenu.addEventListener('click', function() {
var hamburgerMenuSpan2 = document.querySelector('.hamburger-second');
hamburgerMenuSpan2.classList.toggle('hamburger-line-2');
});
.hamburger-menu {
position: absolute;
top: 20px;
right: 20px;
}
.hamburger-line-2 {
animation-name: animate;
animation-duration: 3s;
animation-timing-function: ease-in-out;
animation-fill-mode: forwards;
animation-direction: alternate;
}
@keyframes animate {
0% {
width: 40px;
}
100% {
width: 0px;
}
}
.hamburger-menu span {
display: block;
width: 40px;
height: 2px;
background: black;
margin: 10px 0px;
}
<div class="hamburger-menu">
<span class="hamburger-line-1"></span>
<span class="hamburger-second"></span>
<span class="hamburger-line-3"></span>
</div>
Essentially, I want the hamburger icon line to shrink to 0px width on click with a defined duration, and then expand back to its original width smoothly when clicked again.