Toggling Between Active and Not Active

I am trying to set the navigation tabs to active when I click on the tab. The code that I have here makes the tab active but when I mouse away from the tab and click on another tab, it remains active. How do I get it to become inactive when I go to another tab?

var navbar = document.getElementById("navbar__list");
var tabs = document.getElementsByTagName("li");
for (var i = 0; i < tabs.length; i++) {
  tabs[i].addEventListener("click", function() {
  var current = document.getElementsByClassName("active");
  current[0].className = current[0].className.replace(" active", "");
  this.className += " active";
  });
}

I took away the blank space before active and now it works.

2 Likes

That could be problematic if you have other classes in place or someone adds a class at a later date. You should use a regex to filter the space out if there is one. Also you most likely want to limit the search of the list items to the navbar and not every list that may appear in the page.

Maybe something like this (bearing in mind my JS is basic).

You may also want to test if the active class exists before you apply stuff to it :wink:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.