Trigger two functions with separate onscroll events - JS

Asked

Viewed 110 times

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 to hide part of the navbar of the page by scrolling down the page a little, but by including both, only one of them works. My question is the following, can I only include an onscroll event in the file? Would I have some way to apply both functions in the same file?

Below follow both codes in js that I am using:

Hide the 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; 
};

2 answers

0

You can include multiple functions or codes responding to an event, just do so:

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

You can still use the "good old" addEventListener, thus:

window.addEventListener('scroll', scrollFunction);
window.addEventListener('scroll', outraFunction);
  • 1

    Cara worked perfectly, Thank you very much, I’m learning Javascript still and I’m already with some bushes to solve hehe, thank you very much!

0


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

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

To cancel/stop receiving the event scroll:

window.removeEventListener('scroll', method1);

But there’s also no reason to add 2 listeners scroll p/ fire 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 in a new method, it would be something like this:

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

window.onscroll = function (event) {
  method1(event);
  method2(event);
}
  • 2

    Cara worked perfectly, Thank you very much, I’m learning Javascript still and I’m already with some bushes to solve hehe, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.