Home > OS >  How do I remove the class from the navbar button when a new link is selected [Javascript]
How do I remove the class from the navbar button when a new link is selected [Javascript]

Time:03-06

I am trying to make an active state on my link when clicked, which remains until another link is clicked. I'd like to have the class removed and transferred to the next link when clicked.

Currently it can be toggled on and off on each link.

  document.getElementById('navbar__list').addEventListener("click", function(event){
  event.target.classList.toggle('funcElemStyle');
});

#CSS
    .funcElemStyle{
  background: #333;
}

CodePudding user response:

Instead of using javascript to achive this functionality, you can use CSS to achieve the same effect by using :active.

for example:

/* Selects the link element. */
a:active {
    color: #4444AA;
}

you can also use :hover if you want effects when hovered. CSS also allows chaining so if you want an effect to apply when it is hovered over and active, you can use :active:hover

CodePudding user response:

Instead of toggle use .add() and .remove() functions. Run snippet for an example.

document.querySelector("div").addEventListener("click", event=>{
  event.target.classList.remove("red")
})
div{
  width: 100px;
  height: 100px;
  background: green;
}
.red{
  background: red;
}
<div ></div>

  • Related