1

I am trying to set up a project for use with mobile and desktop but the wheel event doesn't work on mobile, so I need to use scroll.

I know how to get the deltaY from the Wheel event:

window.addEventListener("wheel", event => console.info(event.deltaY));

How do I get the deltaY from the Scroll event?

tony
  • 506
  • 2
  • 17

1 Answers1

1

You should memorize the last scroll position in a variable, and when the scroll event fires, you can compute the difference.

Here is a modified example for your use case from the MDN docs on scroll event:

let lastKnownScrollPosition = 0;
let deltaY = 0;

document.addEventListener('scroll', function(e) {
  let ticking = false;
  if (!ticking) {
    // event throtteling
    window.requestAnimationFrame(function() {
      deltaY = window.scrollY - lastKnownScrollPosition;
      lastKnownScrollPosition = window.scrollY;
      console.log('deltaY', deltaY);
      ticking = false;
    });
    ticking = true;
  }


});
body {
  background: lightgrey;
  height: 8000px;
}
<body>
</body>

The code above uses throtteling in order to reduce the amount of fired events. Also see: Difference Between throttling and debouncing a function

gru
  • 2,319
  • 6
  • 24
  • 39
  • Thanks huge help, however in my tests - I see an identical amount of fired events between the original version you posted and the throttled version. – tony Feb 17 '22 at 22:53
  • My code already uses throtteling. – gru Feb 18 '22 at 08:14
  • before you posted the previous code without the throttling. I tried both and tested them both in the same document and try performed identically – tony Feb 18 '22 at 08:15