Emmanuel
Emmanuel

Reputation: 129

Vanilla Javascript: toggling a class name on each element of a list one so that only item at time has the desired class

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>

Upvotes: 0

Views: 1707

Answers (2)

Emmanuel
Emmanuel

Reputation: 129

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

Upvotes: -1

Palaven
Palaven

Reputation: 21

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>

Upvotes: 2

Related Questions