.scrollLeft()

In this chapter you will learn:

  1. Description for .scrollLeft()(getter)
  2. Get the scroll bar horizontal position
  3. Syntax for .scrollLeft(value) (setter)

.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><!-- j  av  a  2  s  .co m-->
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
             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><!--  j a v a2s .  co m-->
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
             $("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

Next chapter...

What you will learn in the next chapter:

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