jQuery scrollLeft() Method

Last Updated:

jQuery scrollLeft() Method

The jQuery scrollLeft() method is used for the following 2 purpose

  1. To get the current horizontal position of the scroll bar for the first element in the set of matched elements.
  2. To set the current horizontal position of the scroll bar for each of the set of matched elements.

Get Horizontal Position

In the following example, we will get the horizontal position of a div container.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <style> div{ border: 1px solid black; line-height: 2; width: 200px; height: 50px; white-space: nowrap; overflow-x: scroll; } </style> </head> <body> <h1>jQuery scrollLeft() Method</h1> <div> Here is some dummy text to make the div scrollable. Please don't forget to scroll up and down. </div> <p>scroll left is at <span id="point">0</span>px</p> <script> $(document).ready(function(){ var count = 0; $("div").scroll(function(){ count += 1; $("#point").text($("div").scrollLeft()); }); }); </script> </body> </html>

Syntax

$(selector).scrollLeft(x-pos);

Parameter Values

ValueTypeExplanation
x-pos Optional Specifies the horizontal scrollbar position in pixels.

Browser Support

Devicedesktopmobile
Browsergoogle chromesafarifirefoxinternet Exploreredgeoperagoogle chromesafarifirefoxedgeoperaandroid webviewsamsung internet
scrollLeft()YesYesYesYesYesYesYesYesYesYesYesYesYes

Set Horizontal Position

In the following example, we will set the horizontal position of a div container.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <style> div{ border: 1px solid black; line-height: 2; margin-bottom: 10px; width: 200px; height:50px; white-space: nowrap; overflow-x: scroll; } </style> </head> <body> <h1>jQuery scrollLeft() Method</h1> <div> Here is some dummy text to make the div scrollable. Please don't forget to scroll up and down. </div> <button>Move x-pos to litte</button> <script> $(document).ready(function(){ $("button").click(function(){ var myPixel = $("div").scrollLeft() + 40; $("div").scrollLeft(myPixel); }); }); </script> </body> </html>

Share this Page

Meet the Author