Scroll Detection in JavaScript
Scroll Detection
Sometimes, we want to detect scroll direction to fade in a web component or show the user their reading progress of an article, or trigger a widescreen animation, anything! So, in this article, we’ll look at how to detect scroll direction with JavaScript.
Listen for Scroll
We can listen to the scroll event of window to check the scroll direction.
window.onscroll = function(e) {
console.log(this.oldScroll > this.scrollY);
this.oldScroll = this.scrollY;
}
to set a scroll event listener to the window.onscroll property.
Then we get the scrollY value and check if it’s bigger than the oldScroll value.
If it’s bigger, that means we’re scrolling down.
Then we set the scrollY value to the oldScroll property so that we can keep the old scroll value.
Both values are in pixels so we can compare them directly.
Track the Scroll
Next we should listen to the scroll event and Track the pageYOffset Property
We can also use the pageYOffset property to track the location that we’ve scrolled to vertically.
let oldValue = 0
let newValue = 0
window.addEventListener('scroll', (e) => {
newValue = window.pageYOffset;
if (oldValue < newValue) {
console.log("Up");
} else if (oldValue > newValue) {
console.log("Down");
}
oldValue = newValue;
});
to add a scroll listener to window with addEventListener . Then we set newValue to window.pageYOffset . If newValue is bigger than oldValue , then we scrolled up. If newValue is smaller than oldValue , then we scrolled down. In the end, we set newValue to oldValue so we can compare the 2.
Conclusion
We can detect scroll direction with the pageYOffset or the scrollY properties.