JavaScript

How to Detect Scroll Direction on a Page Using JavaScript

Last updated: 02.04.2026
Views: 377

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
});
author
Author: Igor Rybalko
I have been working as a front-end developer since 2014. My main technology stack is Vue.js and WordPress.

Similar posts:

One response to “How to Detect Scroll Direction on a Page Using JavaScript”

  1. Den says:

    Thank you. That’s what I need

Leave a Reply

Your email address will not be published. Required fields are marked *

Blue Captcha Image
Refresh

*