Trigger two functions with different onscroll events - JS

0

Good morning,

I need a help, I have two functions that use the onscroll event, a function to appear a "Back to Top" button where when it is presented to the user it can be triggered and will be returned to the top of the page and another of hiding part of the navbar of the page when descending a little the page, however, when including both, only one of them works. My question is this, can I just include an onscroll event in the file? Is there any way I can apply both functions to the same file?

Below are both the codes in js that I'm using:

Hide NavBar:

var prevScrollpos = window.pageYOffset;

window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;
      if (prevScrollpos > currentScrollPos) {
          document.getElementById("navbar").style.top = "0";
         } else {
    document.getElementById("navbar").style.top = "-50px";
}
prevScrollpos = currentScrollPos;
};

Back to Top button:

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

function scrollFunction() {
    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 
20) {
        document.getElementById("Topo").style.display = "block";
    } else {
        document.getElementById("Topo").style.display = "none";
    }
}

function VoltarTopo() {
    document.body.scrollTop = 0; 
    document.documentElement.scrollTop = 0; 
};
    
asked by anonymous 18.07.2018 / 14:41

2 answers

0

If you use the addEventListener method, you can add more than one method to run at each event.

window.addEventListener('scroll', method1);
window.addEventListener('scroll', method2);

To cancel / stop receiving the scroll event:

window.removeEventListener('scroll', method1);

But you also do not have to add 2 listeners to scroll to trigger two different methods that are on the same page. Following what you have done so far, you can isolate the block that implements your window.onscroll into a new method, it would look something like this:

function method1(event) { ... }
function method2(event) { ... }

window.onscroll = function (event) {
  method1(event);
  method2(event);
}
    
18.07.2018 / 14:52
0

You can include multiple functions or codes by responding to an event, just do the following:

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

You can still use the "good old" addEventListener , like this:

window.addEventListener('scroll', scrollFunction);
window.addEventListener('scroll', outraFunction);
    
18.07.2018 / 14:52