jQuery | scrollTop() with Examples

The scrollTop() method is an inbuilt method in jQuery which is used to return the vertical top position of the scrollbar.

Syntax:

$(selector).scrollTop(position)

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

Return Value: This method returns the top position of the scroll bar.

Below example illustrates the scrollTop() method in jQuery:

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <head>
        <title>scrollTop method</title>
        <script src=
        </script>
          
        <!-- jQuery code to show the working of this method -->
        <script>
            $(document).ready(function() {
                $("button").click(function() {
                    alert($("div").scrollTop() + " px");
                });
            });
        </script>
        <style>
            div {
                border: 1px solid black;
                width: 100px;
                height: 150px;
                overflow: auto;
            }
        </style>
    </head>
    <body>
        <div>
            Welcome to GeeksforGeeks!. Welcome to GeeksforGeeks!. Welcome
            to GeeksforGeeks!. Welcome to GeeksforGeeks!. Welcome to
            GeeksforGeeks!. Welcome to GeeksforGeeks!. Welcome to
            GeeksforGeeks!. Welcome to GeeksforGeeks!. Welcome to 
            GeeksforGeeks!. Welcome to GeeksforGeeks!. Welcome to 
            GeeksforGeeks!. Welcome to GeeksforGeeks!. Welcome to 
            GeeksforGeeks!. Welcome to GeeksforGeeks!. Welcome to 
            GeeksforGeeks!. Welcome to GeeksforGeeks!</div>
        <br>
          
        <!-- move the scroll bar and click on this button -->
        <button>Click Here !</button>
    </body>
</html>

chevron_right


Output:
Before click on the button:

Pixel value of the top position shown in above figure:



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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.