Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiate between scroll up/down in jquery? [duplicate]

Tags:

jquery

scroll

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?

like image 659
Hanna Avatar asked Feb 14 '11 07:02

Hanna


People also ask

How to detect scroll up and scroll down in jQuery?

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.

Is it scroll up or down?

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.

What is scroll event in jQuery?

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.

What is scroll in JavaScript?

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.


2 Answers

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.

like image 155
Gabi Purcaru Avatar answered Oct 09 '22 20:10

Gabi Purcaru


<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
  });
});

like image 43
Iman Sedighi Avatar answered Oct 09 '22 22:10

Iman Sedighi