How to detect the direction of the scroll of a page in JavaScript
Overview
To detect the scroll direction:
- Store the
value of the window in a variable.scrollY The scrollY represents the pixels that the document is currently scrolled vertically. - Listen for the scroll event on the window object.
- When the page scroll happens, compare the previous
scrollYvalue with the currentscrollY. - 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:
Explanation
In the code above:
- Lines 5 to 8: We create a
divelement to indicate the direction of the scroll. We set the element at a fixed position on the top right of the page using theposition:fixedCSS attribute.
- Lines 9 to 11: We create three
divelements with some line break elements (br) so that the page becomes scrollable.
- Line 14: We create a variable
oldScrollYand store thescrollYvalue of the window object.
- Line 16: We add an event listener for the scroll event on the
windowobject. This is executed when the scroll on the page happens. Inside this function, we get the currentscrollYvalue of the window object and compare it with theoldScrollY. If the new value is greater thanoldScrollYthen the scroll direction is downwards. Otherwise, the scroll direction is upwards.
- Line 22: We update the value of the
oldScrollYvariable with the latestscrollYvalue.