I have a sidebarmenu with anchor link. The idea is simple: Once someone clicks on a menuitem that specific item gets the "active" class and the previous "active" menuitem gets that class removed.
Somehow the code doesnt work and I cant figure out why..
Happy to receive some tips and help!
This is the page:
https://www.otto-keller.de/wissenswertes/
function setActive(element){
var menuitems = document.querySelectorAll(".leftmenu_item.active");
[].forEach.call(menuitems, function(el) {
el.classList.remove("active");
});
element.classList.add("active");
}
.active {
color: red;
}
<ul>
<li class="leftmenu_item active" onclick="setActive(this)">
<a href="#daunenfedern">Daunen & Federn</a>
</li>
<li class="leftmenu_item " onclick="setActive(this)">
<a href="#inlett">Inlett</a>
</li>
<li class="leftmenu_item " onclick="setActive(this)">
<a href="#allergiker">Allergiker</a>
</li>
<li class="leftmenu_item " onclick="setActive(this)">
<a href="#waschmittel">Waschmittel</a>
</li>
</ul>
function setActive(element){
var menuitems = document.querySelectorAll(".leftmenu_item.active");
[].forEach.call(elems, function(el) {
el.classList.remove("active");
});
element.classList.add("active");
}
I tried to look first for the element that has the active class already to remove it. Then add the "active" class to the element which was clicked on with onclick().
Somehow it doesnt work on the live page – but in the editor..
2
Answers
Change this
To this
Iterate over the NodeList returned by
document.querySelectorAll()
instead of the[]
like you did earlier. See the correct signature for theforEach
.You can implement this by looping your elements, adding them a
click
event listener which callssetActive
, passing the element to be set to active. InsidesetActive
, we check whether the current element is already active in which case we do nothing. Otherwise, we find the previously active element and, if it exists, then we remove the active class from it and then we proceed adding the active class to the element that was clicked.