To detect the scroll direction:
scrollY
value with the current scrollY
. The code below demonstrates how to detect scroll direction in JavaScript:
In the code above:
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. div
elements with some line break elements (br
) so that the page becomes scrollable. oldScrollY
and store the scrollY
value of the window object.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. oldScrollY
variable with the latest scrollY
value.