JavaScript

How to Detect Scroll Direction on a Page Using JavaScript

Last updated: 09.10.2025
Views: 164

Sometimes it is necessary to detect the direction of vertical scrolling on a site, for example, to perform some actions with the footer or header. Let’s write code to determine the direction.

JavaScript

let lastScrollTop = 0; // Store the last scroll position

window.addEventListener("scroll", function () {
    let scrollTop = window.pageYOffset || 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.pageXOffset 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:

  • jQuery Tabs Plugin
    Tabs are a fairly common element. There are various implementations of this element on the Internet. But often the tabs are overloaded with code filled with effects that ...
  • 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...
  • Simple JavaScript Clock
    There are many examples of clock implementation using JavaScript on the Internet. The implementation options may be different, but they are usually similar. To create a c...

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 *