Sometimes, we want to detect scroll direction with JavaScript.
In this article, we’ll look at how to detect scroll direction with JavaScript.
Listen to the scroll Event
We can listen to the scroll event of window
to check the scroll direction.
For instance, we can write:
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.
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.
For instance, we can write:
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.