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:
-
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...
-
Converting an Image to Base64 Using JavaScript
Converting an image to a Base64 string in JavaScript can be extremely useful in many modern web development scenarios. One of the most common reasons for using Base64 is ...
-
Drop down menu (jQuery)
Drop down menu can be done without JavaScript, only with the help of CSS. With :hover. But the JavaScript menu has its advantages. The most important thing is the delay i...
Thank you. That’s what I need