I have found some great ways to check for where the scroll bar is using jquery, but I was wondering if you can differentiate whether or not the user scrolled up or down?
The scrollTop() method in jQuery is used to set or return the vertical scrollbar position for the selected elements. With the hep of this method, we can find the mouse scroll direction. Parameters: This method accepts single parameter position which is optional.
Pressing page up scrolls up one page or gets you to the top of the page. Pressing page down scrolls down one page at a time or gets you to the bottom of the page. Some people may also refer to the page up and page down keys as the scroll keys, not to be confused with the scroll lock key.
The scroll event occurs when the user scrolls in the specified element. The scroll event works for all scrollable elements and the window object (browser window). The scroll() method triggers the scroll event, or attaches a function to run when a scroll event occurs.
The onscroll event in JavaScript occurs when a scrollbar is used for an element. The event is fired when the user moves the scrollbar up or down. We can use the CSS overflow property for creating a scrollbar. In HTML, we can use the onscroll attribute and assign a JavaScript function to it.
Check for the last state. Something like this:
Keep a variable, say, last_scroll_position
, and when you have a scroll, if last_scroll_position - current_position > 0
, the user scrolled up, and down if it's less than 0.
<script type='text/javascript'>
$(function(){
var CurrentScroll = 0;
$(window).scroll(function(event){
var NextScroll = $(this).scrollTop();
if (NextScroll > CurrentScroll){
//write the codes related to down-ward scrolling here
}
else {
//write the codes related to upward-scrolling here
}
CurrentScroll = NextScroll; //Updates current scroll position
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With