I am trying to create a toggle menu using CSS and JavaScript, but I have encountered an issue where clicking on the bars displays the navbar, but then the bars disappear and there is no option to close the navbar.
<a href="#" class="fas fa-bars" id="menu-icon"></a>
<a href="#" class="logo">flower<span>.</span></a>
<nav class="navbar">
<a href="#home">home</a>
<a href="#about">about</a>
<a href="#contact">contact</a>
<a href="#shop">shop</a>
</nav>
let menuIcon = document.querySelector('.fa-bars');
let menu = document.querySelector('.navbar');
// Add event listener to the menu icon
menuIcon.addEventListener('click', () => {
menuIcon.classList.toggle('fa-bars');
menu.classList.toggle('open');
});
header .fa-bars{
display: block;
}
header .navbar{
position: absolute;
top: 100%; left: 0; right: 0;
background: #eee;
border-top: .1rem solid rgba(0, 0, 0, .1);
display: none;
}
header .navbar a{
padding: 1.5rem;
margin: 1.5rem;
background-color: #fff;
border-top: .1rem solid rgba(0, 0, 0, .1);
display: block;
border-radius: .5rem;
}
header .navbar.open{
display: block;
}
This code works to show the navbar but does not provide a way to close it. When I try to run it, the toggle shows the navbar but doesn't allow for closing it by clicking again.