Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading