October 24, 2024
Chicago 12, Melborne City, USA
HTML

Mobile navbar does not automatically close afer clicking a link inside the navbar


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 abd to remove the status active but after the link being clicked but the code does not work.

Here is my HTML code:

<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>

And here is the JS code:

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'
}



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video