0

I have a navigation bar.
To start with only the first link (Homepage) has a class of 'active'.

I want to achieve the following:

when the user click on a different link the class of active is removed from wherever is present and is attributed to the link the user has clicked. So that only one link at a time is active.

const links = document.querySelectorAll('.navbar ul li a');

links.forEach((link) => {
  link.addEventListener('click', () => {
    link.classList.toggle('active');
  });
});
.active {
  background-color: #fc9d03;
}
<div class="navbar">
  <ul>
    <li><a href="#" class="active">Homepage</a></li>
    <li> <a href="#">Blog Entries</a></li>
    <li><a href="#">Food Gallery</a></li>
    <li> <a href="#">Contact Us</a></li>
  </ul>
</div>
Emmanuel
  • 121
  • 2
  • 11
  • 1
    Instead of just toggling it, remove it from all others, then add it back to the current one: https://jsfiddle.net/rcfx75m9/ –  Nov 09 '20 at 14:20
  • unless your using ajax and xhr, the page will refresh, which will reset the css & javascript to their initial values anyway.. Just a thought.. – Ryan Stone Nov 09 '20 at 14:26
  • Duplicate: [How can I add and remove an active class to an element in pure JavaScript](https://stackoverflow.com/questions/38990163/how-can-i-add-and-remove-an-active-class-to-an-element-in-pure-javascript) –  Nov 09 '20 at 14:27
  • `document.querySelector('.navbar ul li a.active').classList.remove('active'); link.classList.add('active');` – epascarello Nov 09 '20 at 14:38
  • @ChrisG thank you so much for your fiddle. It's very concise and very clear. You taught me something new today! Thanks a lot! – Emmanuel Nov 10 '20 at 08:53

2 Answers2

2

I edited your snippet a little.

On event listener function you can get all links to be deactivated by filtering out the one clicked from all links.

Then you can remove activate class from these links and add it to clicked one.

const links = document.querySelectorAll('.navbar ul li a');

links.forEach((link) => {
  link.addEventListener('click', () => {
    const notClickedLinks = Array.from(links).filter((notClickedLink) => {
      return notClickedLink !== link;
    });

    notClickedLinks.forEach((notClickedLink) => {
      notClickedLink.classList.remove('active');
    });

    link.classList.add('active');
  });
});
.active {
  background-color: #fc9d03;
}
<div class="navbar">
  <ul>
    <li><a href="#" class="active">Homepage</a></li>
    <li><a href="#">Blog Entries</a></li>
    <li><a href="#">Food Gallery</a></li>
    <li><a href="#">Contact Us</a></li>
  </ul>
</div>
Palaven
  • 21
  • 1
  • 1
0

My answer has been provided by @Chris G here in the comments:

Instead of just toggling it, remove it from all others, then add it back to the current one: jsfiddle.net/rcfx75m9 – Chris G 18 hours ago

Emmanuel
  • 121
  • 2
  • 11