How to Detect Scroll Direction on a Page Using JavaScript
Sometimes it is necessary to detect the direction of vertical scrolling on a website in order to dynamically change the behavior of interface elements. For example, this can be useful when working with a header or footer — hiding them while scrolling down to save screen space, and showing them again when the user scrolls up.
Scroll direction detection can also improve user experience in other scenarios, such as triggering animations, loading additional content, or adjusting navigation elements based on how the user interacts with the page. This technique is often used in modern web interfaces to make them feel more responsive and intuitive.
The basic idea behind detecting scroll direction is to compare the current scroll position with the previous one. By tracking how this value changes over time, you can determine whether the user is scrolling up or down and react accordingly.
In the following example, we will implement a simple solution that detects the scroll direction using JavaScript.
JavaScript
let lastScrollTop = 0; // Store the last scroll position
window.addEventListener("scroll", function () {
let scrollTop = window.scrollY || 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.scrollX 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:
-
How to Get Max Value in JavaScript Array
A short note about finding the maximum value in a JavaScript array with numeric values. The Array object in JS does not have its own max method. To find the maximum va...
-
How to Create a Custom jQuery Plugin
The convenience of the jQuery plugin is that you can use the same code several times for different objects. In this case, copy-paste code is not needed. In addition, you ...
-
Simple JavaScript Clock
There are many examples of implementing a clock using JavaScript, and while the approaches may vary slightly, most of them follow a similar idea. Typically, such function...
Thank you. That’s what I need