Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

243
Visualizações
How do I convert this code so the functions can take a variable?

I am trying to change the color of nav bar elements when the mouse goes over them.

This piece of code does that but for only the first button:

let navOne = document.getElementById("nav1");

function mouseOn() {
    nav1.style.color = "red";
}

function mouseOff() {
    nav1.style.color = "black";
}

navOne.addEventListener('mouseover', mouseOn);
navOne.addEventListener('mouseout', mouseOff);

I have been trying to convert the code so the functions work for multiple buttons, but cannot seem to get it to work. Here is the code so far:

let navOne = document.getElementById("nav1");

function mouseOn(navButton) {
    navButton.style.color = "red";
}

function mouseOff(navButton) {
    navButton.style.color = "black";
}

navOne.addEventListener('mouseover', mouseOn(navOne));
navOne.addEventListener('mouseout', mouseOff(navOne));

It has no errors, but does not cause any color change when I move my mouse button over the nav1 element.

Any help is greatly appreciated.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can have the event handler functions take advantage of the event parameter that is passed in:

function mouseOn(e) {
  e.target.style.color = "red";
}

function mouseOff(e) {
  e.target.style.color = "black";
}

for (let navItem of document.querySelectorAll('nav a')) {
  navItem.addEventListener('mouseover', mouseOn);
  navItem.addEventListener('mouseout', mouseOff);
}
nav a {
  display: inline-block;
  padding: 10px;
  color: black;
}
<nav>
  <a href="#" id="nav1">Nav One</a>
  <a href="#" id="nav2">Nav Two</a>
</nav>

However, using a css :hover pseudo-attribute would be the preferred approach nowadays. No JS code needed.

nav a {
  display: inline-block;
  padding: 10px;
  color: black;
}

nav a:hover {
  color: red;
}
<nav>
  <a href="#">Nav One</a>
  <a href="#">Nav Two</a>
</nav>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda