简体   繁体   中英

Two Javascript functions don't work together


I wanted to write some javascript functions for my theme and I'm a newbie in Javascript (So, Please don't laugh at me).
The first function is about navbar that when you scroll 400px, navbar will show from top. And second is about "goto-up" button.

window.onscroll = function() {scrollFunction()};

function scrollFunction() {
    if (document.body.scrollTop > 400 || document.documentElement.scrollTop > 400) {
        document.getElementById("goup").style.bottom = "0";
    } else {
        document.getElementById("goup").style.bottom = "-100px";
    }
};
window.onscroll = function() {goupFunction();};

function goupFunction() {
    if (document.body.scrollTop > 300 || document.documentElement.scrollTop > 300) {
        document.getElementById("navbar").style.top = "0";
    } else {
        document.getElementById("navbar").style.top = "-50px";
    }
};

These two don't work together. I need your help. @Pedram, Fixed my problem. Thanks xD ( I added the second function to the first function and now those works together.)

Whenever you assign to window.onscroll , you overwrite the event handler. Instead, use window.addEventListener and/or put both calls in one function.

So remove all window.onscroll = .. lines and add:

window.addEventListener('scroll', function() {
    scrollFunction();
    groupFunction();
};

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