Shireesha Parampalli
Shireesha Parampalli

Reputation: 324

How to handle two scroll events in a webpage

two js function loads on scroll . Say there is two onscroll events to handle

window.onscroll = function(e) {
  var footerHeight = 500;
  if ((window.innerHeight + window.scrollY + footerHeight) >= document.body.offsetHeight) {
    if (branchLoaded == false) {
      loadBranch1();
    };
  }
};

window.onscroll = function(e) {
  var footerHeight = 500;
  if ((window.innerHeight + window.scrollY + footerHeight) >= document.body.offsetHeight) {
    if (branchLoaded == false) {
      loadBranch2();
    };
  }
};

Upvotes: 1

Views: 1607

Answers (1)

Sagar V
Sagar V

Reputation: 12478

In your code, the second event handler is overriding the first one.

This is similar to <element onload="function(){}" onload="function(){}">. In it, Only the latter one will execute.

Example

window.onscroll = function(){console.log(1)}
window.onscroll = function(){console.log(2)}
<div>Test<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>Bottom</div>

Solution

You need addEventListener to set up multiple Event Listener.

window.addEventListener('scroll',function(){console.log(1)});
window.addEventListener('scroll',function(){console.log(2)});
<div>Test<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>Bottom</div>

Upvotes: 3

Related Questions