How to Detect Scroll Direction on a Page Using JavaScript
Last updated: 09.10.2025
Views: 164
Sometimes it is necessary to detect the direction of vertical scrolling on a site, for example, to perform some actions with the footer or header. Let’s write code to determine the direction.
JavaScript
let lastScrollTop = 0; // Store the last scroll position
window.addEventListener("scroll", function () {
let scrollTop = window.pageYOffset || document.documentElement.scrollTop;
if (scrollTop > lastScrollTop) {
console.log("Scrolling Down");
} else if (scrollTop < lastScrollTop) {
console.log("Scrolling Up");
}
lastScrollTop = scrollTop; // Update the last scroll position
});
To determine the horizontal scroll direction, use window.pageXOffset or document.documentElement.scrollLeft.
I sometimes also use jQuery in some projects. Let’s write the same thing using jQuery
jQuery
let lastScrollTop = 0; // Store the last scroll position
$(window).on('scroll', function(){
let scrollTop = $(this).scrollTop();
if (scrollTop > lastScrollTop) {
console.log("Scrolling Down");
} else if (scrollTop < lastScrollTop) {
console.log("Scrolling Up");
}
lastScrollTop = scrollTop; // Update the last scroll position
});
Similar posts:
-
jQuery Tabs Plugin
Tabs are a fairly common element. There are various implementations of this element on the Internet. But often the tabs are overloaded with code filled with effects that ...
-
Working with Cookies in JavaScript
Сookie (web cookie or browser cookie) is a string of information that can be stored in a browser and sent to the server. The maximum size for one cookie is 4096 bytes. T...
-
Simple JavaScript Clock
There are many examples of clock implementation using JavaScript on the Internet. The implementation options may be different, but they are usually similar. To create a c...
Thank you. That’s what I need