How to detect the direction of the scroll of a page in JavaScript

Overview

To detect the scroll direction:

  • Store the scrollY The scrollY represents the pixels that the document is currently scrolled vertically. value of the window in a variable.
  • Listen for the scroll event on the window object.
  • When the page scroll happens, compare the previous scrollY value with the current scrollY .
  • If the current value is greater than the old value, then the scroll direction is downwards. Otherwise, the scroll direction is upwards.
  • Update the current scroll position to the variable.

Example

The code below demonstrates how to detect scroll direction in JavaScript:

Deecting scroll direction

Explanation

In the code above:

  • Lines 5 to 8: We create a div element to indicate the direction of the scroll. We set the element at a fixed position on the top right of the page using the position:fixed CSS attribute.
  • Lines 9 to 11: We create three div elements with some line break elements (br) so that the page becomes scrollable.
  • Line 14: We create a variable oldScrollY and store the scrollY value of the window object.
  • Line 16: We add an event listener for the scroll event on the window object. This is executed when the scroll on the page happens. Inside this function, we get the current scrollY value of the window object and compare it with the oldScrollY . If the new value is greater than oldScrollY then the scroll direction is downwards. Otherwise, the scroll direction is upwards.
  • Line 22: We update the value of the oldScrollY variable with the latest scrollY value.

Free Resources