So I've got this JS mobile nav menu. When the menu button is clicked the menu opens, and can then be closed by pressing the menu button again. I also want the menu to close when one of the nav items is clicked. With the code below, I managed to make the menu close when the first item is clicked but for reasons unknown to myself it doesn't work for the other three nav items. Has it maybe got something to do with the way I'm selecting the nav-item
class? Also, my Javascript knowledge is very limited so there might be something obvious I'm missing.
HTML
<nav class="main-nav">
<a href="#" class="nav-menu"><i class="fa fa-bars" aria-hidden="true"></i></a>
<div class="sidebar is-hidden">
<ul>
<li><a class="nav-item page-scroll" href="#about">ABOUT</a></li>
<li><a class="nav-item page-scroll" href="#framing">FRAMING</a></li>
<li><a class="nav-item page-scroll" href="#gallery">GALLERY</a></li>
<li><a class="nav-item page-scroll" href="#contact">CONTACT</a></li>
</ul>
</div>
</nav>
JS
const button = document.querySelector('.nav-menu')
const sidebar = document.querySelector('.sidebar')
const item = document.querySelector('.nav-item')
button.addEventListener('click', function (e) {
e.preventDefault();
sidebar.classList.toggle('is-hidden')
});
item.addEventListener('click', function () {
sidebar.classList.toggle('is-hidden')
});
Method document.querySelector
returns first found element. If you want to add event listener to more than one element, you should use document.querySelectorAll
method instead. You will receive a list of elements. You want to add event listener to each of them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.