Click State on In-Page Links

General Development Theme Development Classes / Styling Javascript

Snippet Overview

Click State on In-Page Links

Sometimes you might have a menu at the top of a page that links you down to sections of that page. Depending on how the code is structured it may not always reflect the item that you selected if that item is on the current page. To remedy this you can use a little bit of Javascript to add a .active click class to any of the items within that list that are clicked on. The script below toggles on the click class if you select a link but toggles it off if you click on another link. This is super handy when creating lit states on those menu items. So here is what you need to make the magic happen. Please note that this goes on the assumption that your menu is built using a standard ul and li structure of list items.

Step 1

Add the Javascript below to either the header or footer of your site and modify the ID that it targets to match the surrounding div on your menu. Change code below where it says customMenu to whatever the name of your ID is. Note: If you are developing a WordPress theme you can enqueue this Javascript with a function in your themes functions.php file.

var specialNav = document.getElementById("customMenu");

if (specialNav) {
  var navItems = specialNav.getElementsByTagName('li');
  var i;
  for (i = 0; i < navItems.length; i++) {
    navItems[i].addEventListener("click", function() {
      if (!this.classList.contains('active')) {
        clearActives(navItems);
        this.classList.toggle('active');
      }
    });
  }
}

function clearActives(classlist) {
  if (classlist) {
    for (i = 0; i < classlist.length; i++) {
      classlist[i].classList.remove('active');
    }
  }
}

Step 2

Find the current li class for your menu and add an active state. So for example if your html looks like this:

<div id="customMenu">
  <ul>
    <li class="active"> 1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
  </ul>
</div>

Your styles might look something like this:

#customMenu li {
  color: #222;
  background: #ccc;
  padding: 20px 30px;
  margin-right: 10px;
  display: inline-block;
  cursor: pointer;
}

#customMenu li.active {
  color: #fff;
  background: #222;
}

Source: https://codereview.stackexchange.com/questions/222042/toggling-only-a-single-class-as-active-in-a-list

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply