jQuery .scrollLeft() gets and sets horizontal position of the scroll bar

.scrollLeft()(getter) Description

.scrollLeft() (getter)

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

Its return value is the horizontal scroll position in pixels.

The horizontal scroll position is the number of pixels that are hidden from view to the left of the scrollable area.

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

Get the scroll bar horizontal position

The following code displays the scroll bar horizontal position.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--  w w  w.  ja  va  2s. co m-->
             alert($("div").scrollLeft());
        });
    </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

Syntax for .scrollLeft(value) (setter)

.scrollLeft(value) (setter)

sets the current horizontal position of the scroll bar for each of the set 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 horizontal position of the scroll bar to 300px.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from   www. ja  v a  2 s . c  om-->
             $("div").scrollLeft(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





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities