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 Make Asynchronous Requests in a Loop in JavaScript
Implementing asynchronous requests inside a JavaScript loop may not seem obvious at first. When making asynchronous requests inside a JavaScript loop, it is important to ...
-
Smooth Scrolling to Anchor Using JavaScript
Smooth scrolling is a popular web design feature that enhances user experience by allowing seamless navigation between sections of a webpage. Instead of abrupt jumps, smo...
-
Countdown Timer in JavaScript
Countdown timers are commonly used on websites that promote products, services, or special offers. You can often see them on landing pages or in online stores, where they...
Thank you. That’s what I need