How to determine the direction of a jQuery scroll event?

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.

Syntax:

$(selector).scrollTop(position)

Parameters: This method accepts single parameter position which is optional. It is used to specify the vertical scrollbar position in pixels.

Return Value: It returns the vertical position of the scrollbar of selected element.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        Determine the direction of scroll event
    </title>
      
    <script src=
    </script>
      
    <style>
        html, body {
            height: 300%
        }
          
        div {
            position: fixed;
            padding-left: 10px;
            padding-top: 30px;
            height: 10%;
            width: 35%;
            background: lightgrey;
            font-weight: bold;
            border: 2px solid green;
        }
    </style>
</head>
  
<body>
  
    <div></div>
      
    <!-- Script to determine the direction
    of a jQuery scroll event -->
    <script>
        var position = $(window).scrollTop();
  
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();
            if (scroll > position) {
                console.log('scrollDown');
                $('div').text('Scrolling Down Scripts');
            } else {
                console.log('scrollUp');
                $('div').text('Scrolling Up Scripts');
            }
            position = scroll;
        });
    </script>
</body>
  
</html>                    

chevron_right


Output:

  • Scrolling in up direction:
  • Scrolling in down direction:


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.