jQuery scrollLeft() Method

You are Here:

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-posOptionalSpecifies the horizontal scrollbar position in pixels.

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>

Reminder

Hi Developers, we almost covered 99.5% of jQuery Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in jQuery.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author