skip to Main Content

I’m working on a one-pager ([https://rnp.mijnbaron.be/]) and I’m trying to add / remove an active class to the menu items if clicked. I already got 1 part working (adding), but I’m struggling with how to remove the active class from the element, if another menu item is clicked.
And preferably without use of jquery.

Here’s what I’ve got so far:

"use strict";

// Select all scrollable links

const scrollEls = document.querySelectorAll(".scroll a");

// For each scrollEL add eventlistener and function if clicked

for (let i = 0; i < scrollEls.length; i++) {
  scrollEls[i].addEventListener("click", function () {

    if (!scrollEls[i].classList.contains("active")) {
      scrollEls[i].classList.add("active");
    } else {

      scrollEls[i].classList.remove("active");
    }
  });
}

I have tried resetting all active items (removing active class) after the click event by using every, but this does not work. Maybe my thought process is wrong 🙂

2

Answers


  1. Chosen as BEST ANSWER

    I already found out the answer :) Just posting it here, maybe anyone else can use this.

    "use strict";
    
    // Select all scrollable links
    
    const scrollEls = document.querySelectorAll(".scroll a");
    
    // For each scrollEL add eventlistener and function if clicked
    
    for (let i = 0; i < scrollEls.length; i++) {
      // add event listener and add / remove active class to current clicked item
    
      scrollEls[i].addEventListener("click", function () {
        // if clicked on other scrollable item, active class should be for all items except the one that was clicked removed
    
        scrollEls.forEach((element) => {
          element.classList.remove("active");
        });
    
        if (!scrollEls[i].classList.contains("active")) {
          scrollEls[i].classList.add("active");
        }
      });
    }


  2. You can attach listener to the parent element and toggle class based on event target.

    "use strict";
    
    const parent = document.querySelector(".scroll");
    
    parent.addEventListener("click", (ev) => {
      parent.querySelectorAll("a").forEach((el) =>
        el.classList.toggle("active", el === ev.target)
      );
    });
    .scroll li {
      list-style:none;
       display:inline-block;
     }
    .scroll a{
      padding:10px;
      text-decoration:none;
      display:block;
     }
    .scroll a.active {
      background:black;
      color:white;
     }
      <nav>
        <ul class="scroll">
          <li><a href="#">1</a></li>
          <li><a href="#">2</a></li>
          <li><a href="#">3</a></li>
        </ul>
      </nav>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search