Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!