简体   繁体   中英

Making JS EventListener run constantly

A couple of days ago someone here offered me a solution for a script that changes the color of a div when scrolling.

This is the code I used:

    const x = document.getElementById("menuID");
window.addEventListener("scroll", () => {
    if(window.pageYOffset >= 105 && window.pageYOffset < 775){
        x.classList.add("color1");
    } else {
        x.classList.add("color2");
    }
});

It works, nevertheless I want it to keep functioning after the page loaded, so its able to change to ''color.2''. Is this possible?

Add one more event listener on you document and run the same callback from there also :

const x = document.getElementById("menuID");
function callback(){
    if(window.pageYOffset >= 105 && window.pageYOffset < 775){
        x.classList.add("color1");
    } else {
        x.classList.add("color2");
    }
}

window.addEventListener("scroll",callback);
window.addEventListener("load",callback);

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