Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does debouncing scroll events in JS/JQuery work?

The scroll events trigger way more often than I want them to. All it should do is give the .swap class to the next Sibling if you scroll down (followed by an animation) and get rid of the .swap class of the current Element. Same thing just for upwards. What happens now is that it just basically goes to the last element and the first one if scrolled down/up. It is a one-pager which just switches in between different divs.

I've tried Debouncing, Throttling, and requestAnimationFrame but haven't been successful so far. For example: https://css-tricks.com/debouncing-throttling-explained-examples/

Thanks a lot!

HTML:

<div class="div1 swap">
  <h1>Hello</h1>
</div>
<div class="div2">
  <h1>Stack</h1>
</div>
<div class="div3">
  <h1>Overflow</h1>
</div>
<div class="div4">
  <h1>Please</h1>
</div>
<div class="div5">
  <h1>Help</h1>
</div>

CSS:

.div1, .div2, .div3, .div4, .div5{
  visibility: hidden;
  position: fixed;
}
.swap{
  visibility: visible;
  -webkit-animation: slide-in-left .8s ease-out both;
          animation: slide-in-left .8s ease-out both;
}

JS:

window.onscroll = function(event) {
  var aktiv = document.querySelector('.swap');
  if(this.oldScroll > this.scrollY){
    console.log("Up");
    aktiv.previousElementSibling.classList.toggle('swap')
    aktiv.classList.toggle('swap')
  }
  else{
    console.log("Down");
    aktiv.nextElementSibling.classList.toggle('swap')
    aktiv.classList.toggle('swap')
  }
  this.oldScroll = this.scrollY;
}
like image 921
ridonibishi Avatar asked Apr 22 '26 20:04

ridonibishi


1 Answers

Add some threshold for scroll distance, as now even if you scroll 1px. you show next element.

window.onscroll = function(event) {
  var aktiv = document.querySelector('.swap');
  var diff = this.oldScroll - this.scrollY;
  var delta = 100; // Or some element height

  // If scolled too little - do nothing
  if (Match.abs(diff) <= delta) {
     return;
  }

  if(diff < 0){
    console.log("Up");
    aktiv.previousElementSibling.classList.toggle('swap')
    aktiv.classList.toggle('swap')
  }
  else{
    console.log("Down");
    aktiv.nextElementSibling.classList.toggle('swap')
    aktiv.classList.toggle('swap')
  }
  this.oldScroll = this.scrollY;
}

To debounce event use setTimeout:

var timer;

window.onscroll = function (event) {
    var self = this;
    clearTimeout(timer);
    timer = setTimeout(function () {
        [...rest of code...]
    }, 50)
}
like image 54
Justinas Avatar answered Apr 25 '26 08:04

Justinas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!