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
I already found out the answer :) Just posting it here, maybe anyone else can use this.
You can attach listener to the parent element and toggle class based on event target.