Reputation: 1
I created a responsive mobile navbar with a toggle button. One can open and close the toggle button by clicking on it. However when the links inside the mobile navbar are clicked, the page scrolls down to the respective section but the mobile navbar remains open.
I tried to create a cons links and select all the links with getElementById and to remove the status active but after the link being clicked but the code does not work.
const toggleBtn = document.querySelector('.toggle-btn')
const toggleBtnIcon = document.querySelector('.toggle-btn i')
const dropDownMenu = document.querySelector('.dropdown-menu')
toggleBtn.onclick = function() {
dropDownMenu.classList.toggle('open')
const isOpen = dropDownMenu.classList.contains('open')
toggleBtnIcon.classList = isOpen ? 'fa-solid fa-xmark' : 'fa-solid fa-bars'
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css"/>
<button class="toggle-btn"><i class="fa-solid fa-bars"></i></button>
<div class="dropdown-menu">
<ul>
<li><a href="#home" id="links">Home</a></li>
<li><a href="#about" id="links">About</a></li>
<li><a href="#projects" id="links">Projects</a></li>
<li><a href="#contact" id="links">Contact</a></li>
</ul>
</div>
Upvotes: -2
Views: 53
Reputation: 141
Change from id to class as id names cannot be same so
<div class="dropdown-menu">
<ul>
<li><a href="#home" class="links">Home</a></li>
<li><a href="#about" class="links">About</a></li>
<li><a href="#projects" class="links">Projects</a></li>
<li><a href="#contact" class="links">Contact</a></li>
</ul>
Add this into your Js your code will work
const links = document.querySelectorAll('.links')
links.forEach(link => {
link.addEventListener('click', () => {
dropDownMenu.classList.remove('open')
toggleBtnIcon.classList = 'fa-solid fa-bars'
}); });
Working Demo
const toggleBtn = document.querySelector(".toggle-btn")
const toggleBtnIcon = document.querySelector(".toggle-btn i")
const dropDownMenu = document.querySelector(".dropdown-menu")
toggleBtn.onclick = function() {
dropDownMenu.classList.toggle("open")
const isOpen = dropDownMenu.classList.contains("open")
toggleBtnIcon.classList = isOpen ? "fa-solid fa-xmark" : "fa-solid fa-bars"
}
// ADDED
const links = document.querySelectorAll(".links")
links.forEach((link) => {
link.addEventListener("click", () => {
dropDownMenu.classList.remove("open")
toggleBtnIcon.classList = "fa-solid fa-bars"
})
})
.dropdown-menu {
display: none;
}
.dropdown-menu.open {
display: initial;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css" />
<button class="toggle-btn"><i class="fa-solid fa-bars"></i></button>
<div class="dropdown-menu">
<ul>
<li><a href="#home" class="links">Home</a></li>
<li><a href="#about" class="links">About</a></li>
<li><a href="#projects" class="links">Projects</a></li>
<li><a href="#contact" class="links">Contact</a></li>
</ul>
</div>
Upvotes: 2