So I am trying to use the JavaScript on scroll
to call a function. But I wanted to know if I could detect the direction of the the scroll without using jQuery. If not then are there any workarounds?
I was thinking of just putting a 'to top' button but would like to avoid that if I could.
I have now just tried using this code but it didn't work:
if document.body.scrollTop <= 0 {
alert ("scrolling down")
} else {
alert ("scrolling up")
}
It can be detected by storing the previous scrollTop value and comparing the current scrollTop value with it.
JS :
You can get the scrollbar position using
document.documentElement.scrollTop
. And then it is simply matter of comparing it to the previous position.You can try doing this.
Simple way to catch all scroll events (touch and wheel)
Use this to find the scroll direction. This is only to find the direction of the Vertical Scroll. Supports all cross browsers.
Example
This is an addition to what prateek has answered.There seems to be a glitch in the code in IE so i decided to modify it a bit nothing fancy(just another condition)