Skip to content
Related Articles

Related Articles

Improve Article

How to determine the direction of a jQuery scroll event?

  • Last Updated : 23 May, 2019
Geek Week

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:




<!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>                    

Output:

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



My Personal Notes arrow_drop_up
Recommended Articles
Page :