How to Detect the Scroll Direction in JavaScript
Detecting whether a user is scrolling up or down is a common requirement for creating dynamic and responsive user interfaces. This is the key to building features like auto-hiding navigation bars, revealing animations on scroll, or creating infinite-scroll content loaders.
This guide will teach you the modern, standard method for detecting the scroll direction by listening to the scroll event. You will also learn about the critical performance considerations and understand the important difference between the scroll and wheel events.
The Core Logic: Comparing Scroll Positions
The logic for detecting the scroll direction is simple:
- Store the last known scroll position in a variable.
- When a scroll event occurs, get the new, current scroll position.
- Compare the current position to the last position:
- If
currentScroll > lastScroll, the user is scrolling down. - If
currentScroll < lastScroll, the user is scrolling up.
- If
- After the check, update the "last scroll" variable to the current position for the next event.
The Modern Solution (Recommended): The scroll Event Listener
The scroll event is the definitive tool for this task, as it fires whenever the document's scroll position changes, regardless of what caused it (mouse wheel, scrollbar drag, keyboard navigation, etc.).
For example, we want to know whether the user is scrolling up or down the page.
Solution: this code sets up a single event listener on the window to track the scroll position.
// A variable to store the last known scroll position
let lastScrollTop = window.scrollY || document.documentElement.scrollTop;
window.addEventListener('scroll', () => {
const scrollTopPosition = window.scrollY || document.documentElement.scrollTop;
if (scrollTopPosition > lastScrollTop) {
console.log('Scrolling Down');
} else if (scrollTopPosition < lastScrollTop) {
console.log('Scrolling Up');
}
// Update the last scroll position
// Set to 0 to handle going all the way back to the top
lastScrollTop = scrollTopPosition <= 0 ? 0 : scrollTopPosition;
});
How it works:
window.scrollY: This is the modern, standard property that returns the number of pixels the document is currently scrolled vertically. Thedocument.documentElement.scrollTopis included for compatibility with older browsers.addEventListener('scroll', ...): This attaches our function to thescrollevent.- The
if/else ifblock performs the core comparison logic. - The final line updates
lastScrollTopfor the next event.
A Crucial Consideration: Performance and Throttling
The scroll event can fire extremely rapidly—many times per second—while a user is scrolling. If the code inside your event handler is complex (e.g., it performs DOM manipulations or complex calculations), it can cause performance issues and make the page feel sluggish.
Best Practice: For any production application, you should throttle your scroll handler. Throttling is a technique that ensures your function is executed at most once every X milliseconds (e.g., once every 100ms).
Example:
// This is a conceptual example. In a real project, you would use a utility
// function from a library like Lodash, or write your own.
let isThrottled = false;
window.addEventListener('scroll', () => {
if (!isThrottled) {
// Run your scroll logic here...
isThrottled = true;
setTimeout(() => {
isThrottled = false;
}, 100); // Only allow the logic to run every 100ms
}
});
Understanding the Difference: scroll vs. wheel Event
You might be tempted to use the wheel event, but it is often the wrong tool for this job.
| Event | scroll | wheel |
|---|---|---|
| What it tracks | The result: the document's scroll position has changed. | The action: the user has physically moved their mouse wheel. |
| Fired by | Mouse wheel, scrollbar drag, keyboard (arrow keys, spacebar), touch gestures. | Mouse wheel only. |
| Reliability | High. It directly reflects the visual scroll position. | Low. Does not fire for scrollbar drags. Can stop firing even if momentum scrolling continues. |
Rule of Thumb: Use the scroll event when you care about where the user is on the page. Use the wheel event only when you need to intercept the direct input from the mouse wheel itself, for example, to implement custom zooming on a map.
Conclusion
Detecting the scroll direction is a straightforward task if you use the right browser event.
- The
scrollevent is the definitive and most reliable tool for this job. - The core logic involves comparing the current scroll position (
window.scrollY) to the last known position. - For any real-world application, you must consider performance and throttle your scroll event handler to prevent the UI from becoming sluggish.
- Avoid using the
wheelevent for this task, as it only tracks the mouse wheel action, not the actual scroll position of the page.