The jQuery scrollTop method is used to set or return the vertical scrollbar position for the selected element. When the scrollbar is on the top, it specifies the position 0.
Syntax:
To return vertical scrollbar position:
$(selector).scrollTop()
Parameter | Description |
---|---|
Position | It specifies the vertical scrollbar position in pixels. |
Let's take an example to demonstrate the jQuery scrollTop() method.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ alert($("div").scrollTop() + " px"); }); }); </script> </head> <body> <div style="border:1px solid black;width:150px;height:100px;overflow:auto"> Twinkle, twinkle, little star,How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are!</div><br> <button>Return the vertical position of the scrollbar</button> <p>Move the scrollbar down and click the button again.</p> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>scrollTop demo</title> <style> div.demo { background: #7fffd4 none repeat scroll 0 0; border: 3px solid #666; margin: 5px; padding: 5px; position: relative; width: 200px; height: 150px; overflow: auto; } p { margin: 10px; padding: 5px; border: 2px solid #666; width: 1000px; height: 1000px; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <div class="demo"><h1>Welcome to:</h1><p>rookienerd.com</p></div> <script> $( "div.demo" ).scrollTop( 300 ); </script> </body> </html>