Skip to content
Advertisement

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.

Answer

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>
Advertisement