简体   繁体   中英

Functions fires regardless of the eventListeners

I am trying to change the background of the section when the user is viewing it, however, when I added the eventlistners they didn't work properly. they fire as if there were no eventlistners. your assistance is much appreciated.

please find my JS code below

const sections = document.querySelectorAll("section");

// this function changes the background of the section to show it is the active one
const activeSection = section => {
  section.style.backgroundColor = "#6BCAE2";
};

// this function return the section to its normal status when the user is not viewing it anymore
const inactiveSection = section => {
  section.style.backgroundColor = "";
};

// to loop throught the nodelist and add eventlistneres for the functions above
for (let section of sections) {
  section.addEventListener("mouseover", activeSection(section));
  section.addEventListener("mouseout", inactiveSection(section));
}

You need to use an anonymous function to pass in your parameter:

for (let section of sections) {
  section.addEventListener("mouseover", () => { activeSection(section); });
  section.addEventListener("mouseout", () => { inactiveSection(section); });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM