The jQuery scrollLeft() method can be used to get or set the position of the horizontal scrollbar. It finds the position of the scrollbar from the left side of the selected element.
Syntax
The syntax of this method is given below:-
Description of the Parameters
The description of the parameters is given below.
Parameter Name | Description |
---|---|
selector | Specify the selector to select the elements and set or get the scrollbar position. You have to use tag name, class name, or id of the elements to select. |
position | It is the value of the position to set the horizontal scrollbar of the selected element. It is in the pixel. |
Example to Get Position Using jQuery scrollLeft() Method
If you want to get the position of the horizontal scroll bar of the selected element. You have to use this method without any parameters. The below example contains the div element and the button. The div element contains a horizontal scroll bar to check its position using the method.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<script> $(document).ready(function(){ $('.mygetbtn').click(function(){ var mypos = $("div").scrollLeft(); alert(mypos); }); }); </script> <style> div{ border: 1px solid #ccc; width: 200px; height: 120px; overflow: auto; } </style> <button type="button" class="mygetbtn">Click to Return Position</button><br><br> <div>Welcomeummmmmmmmmmmmmmmmmmmmmmmmmmmmmmm to Tutorial! Learn jQuery with live examples. Welcome to Tutorial! Learn jQuery with live examples.</div> <p>Scroll the above horizontal scroller and click the button to find the position.</p> |
Output
Scroll the above horizontal scrollbar and click the button to find the position.
You have to click the button given above to get the position of the selected element. Scroll the scrollbar to the right direction and click the button. It displays the position in the pixel in an alert box.
Set the Horizontal Scroll Bar Position
You can also set the position of the scroll bar of the selected element. pass the value in a pixel as the parameter of the jQuery scrollLeft() method.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<script> $(document).ready(function(){ $('.mysetbtn').click(function(){ $("div").scrollLeft(150); }); }); </script> <style> div{ border: 1px solid #ccc; width: 200px; height: 120px; overflow: auto; } </style> <button type="button" class="mysetbtn">Click to Set Position</button><br><br> <div>Welcomeummmmmmmmmmmmmmmmmmmmmmmmmmmmmmm to Tutorial! Use live examples to learn.</div> |
Output
When you click the button given above, it sets the position of the selected element in the right direction. If you move the scroll bar to left or right and click the button, it takes you again to the specified pixel position.
You may also like to read
I hope you like this tutorial on jQuery scrollLeft() method. If you have any queries regarding the tutorial, please comment below.
References