const button = document.getElementById("hamburger");
const list = document.getElementById("list");
button.addEventListener("click", () => {
list.classList.toggle('show');
});
margin: 0;
padding: 0;
box-sizing: border-box;
}
html{
scroll-behavior: smooth;
}
ul{
list-style-type: none;
}
.list{
list-style-type: none;
display: none;
}
.list.show{
position: fixed;
display: block;
inset: 0 0 0 0;
z-index: 99;
text-align: center;
background-color: hsl(0 0% 0% / 0.6);
padding: min(43vh, 20rem) 2rem;
}
header{
display: flex;
justify-content: space-between;
}
.hamburger{
width: 50px;
height: 50px;
background-color: red;
cursor: pointer;
position: absolute;
z-index: 999;
}
h1{
margin: 20rem 0;
}
.contents{
position: absolute;
left: 50%;
top: 120%;
transform: translate(-50%, -50%);
}
<header>
<div class="hamburger" id="hamburger"></div>
<ul class="list" id="list">
<li><a href="#home">HOME</a></li>
<li><a href="#services">SERVICES</a></li>
<li><a href="#about">ABOUT</a></li>
<li><a href="#menu">MENU</a></li>
</ul>
</header>
<div class="contents">
<h1 id="home">HOME</h1>
<h1 id="services">SERVICES</h1>
<h1 id="about">ABOUT</h1>
<h1 id="menu">MENU</h1>
</div>
I am trying to toggle off the eventlistener, when any of the navigation links are clicked. Once it scrolls to the link using the link reference in the html, I want the 'show' to toggle off, So its going to scroll to the link and toggle off the evebtlistener. I've tried using the if else and some other html special class, Please can anyone help me solve this
Can you try adding a shared-class to the navigation items and then use document.querySelectorAll to add a click event listener to them? Something like -
<ul class="list" id="list">
<li><a href="#home" class="nav-item">HOME</a></li>
<li><a href="#services" class="nav-item">SERVICES</a></li>
<li><a href="#about" class="nav-item">ABOUT</a></li>
<li><a href="#menu" class="nav-item">MENU</a></li>
</ul>
And then -
const navItems = document.querySelectorAll('nav-item')
navItems.forEach((navItem) => {
navItem.addEventListener('click', () => {
list.classList.remove("show")
})