.scrollTop()

In this chapter you will learn:

  1. Syntax for .scrollTop()(getter)
  2. Syntax for .scrollTop(value) (setter)

Syntax for .scrollTop()(getter)

.scrollTop()(getter)

gets the current vertical position of the scroll bar for the first element in the set of matched elements.

Its return value is the vertical scroll position in pixels.

If the scroll bar is at the very top, or if the element is not scrollable, this number will be 0.

The following code gets the scroll top offset.

<html><!--from jav  a2  s  . c  om-->
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
             var p = $("p:first");
             $("p:last").text( "scrollTop:" + p.scrollTop() );
        });
    </script>
  </head>
  <body>
    <body>
       <p>Hello java2s.com</p>
    </body>
</html>

Click to view the demo

Syntax for .scrollTop(value) (setter)

.scrollTop(value) (setter)

sets the current vertical position of the scroll bar for each of the sets of matched elements.

value is an integer indicating the new position to set the scroll bar to.

Its return value is the jQuery object, for chaining purposes.

The following code sets the vertical scroll bar value.

<html><!--from   j ava 2  s .  c  o m-->
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
             $("div").scrollTop(300);
        });
    </script>
    <style>
    div{
        width:200px;
        height:100px;
        overflow:auto;
    }
    h1 { width:1000px;height:1000px; }
  </style>

  </head>
  <body>
    <body>
       <div><h1>java2s.com</h1></div>
    </body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. Syntax and Description for .slice() method
  2. Slice from start to middle
  3. Slice from start to the end
  4. Slice a UL list