I am trying to make a highlight effect on Button 1 (bold and blue text with a css class). But of course the class should be removed from Button 1 when i click on another Button in the Menu.
let buttons = document.querySelectorAll(".ef-button");
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function () {
if (buttons[i].classList.contains("active-element")) {
buttons[i].classList.remove("active-element");
} else {
buttons[i].classList.add("active-element");
}
})
}
This is what i wrote. I can click on every button to highlight it, but when i click on another button it does not remove the class from the first button... Anyways, i can click on a already highlighted button to remove the class again.
What i need is like a "reset" that removes the class from the button i clicked on.
When i click on Buttons:
this way:
for those who want to avoid searching in the MDN Doc1
document
.querySelectorAll('.ef-button')
.forEach( (btClickEv,_,buttons) =>
{
btClickEv.onclick = () =>
buttons.forEach(bt=>bt.classList.toggle('active-element',bt===btClickEv))
})
.ef-button { background : pink; }
.active-element { background : green; }
<button class="ef-button"> bt1 </button>
<button class="ef-button"> bt2 </button>
<button class="ef-button"> bt3 </button>
<button class="ef-button"> bt4 </button>
<button class="ef-button"> bt4 </button>