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?
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