scrollTop()

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.

  • To return the position: When this method is used to return the position, it provides the current vertical position of the first matched element in the set.
  • To set the position: When this method is used to set the position, it sets the vertical position of the scrollbar for all matched element.

Syntax:

To return vertical scrollbar position:

snippet
$(selector).scrollTop()

Parameters of jQuery scrollTop() method

Parameter Description
Position It specifies the vertical scrollbar position in pixels.

Example of jQuery scrollTop() method

Let's take an example to demonstrate the jQuery scrollTop() method.

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

Another example of jQuery scrollTop()

snippet
<!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>
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +