jQuery scrollLeft() Method

jQuery | scrollLeft() Method: Learn about the jQuery scrollLeft() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 18, 2022

scrollLeft() Method

You must have visited different websites where once when you are at the right of the page by horizontal scrolling, there is an option to go to the left all in one go. So, if you want to go to the very start of the document again, then you may click on that button. Therefore, it takes you up to the left of the page. This is what the scrollLeft() method of jQuery does.

The scrollLeft() method helps to set or return the horizontal scroll bar position for the selected elements in jQuery. The value of the scroll bar position will be zero pixel if the horizontal scroll bar is at the very left, i.e., it cannot scroll left anymore. This method will reach you up to the point where the position of the scroll bar is mentioned. If the scrollbar position is set to 0px – it will take you to the left of most of the document.

scrollLeft() Method Syntax

$(selector).scrollLeft(position);
$(selector).scrollLeft();

Therefore, this method takes in the scrollbar position as its parameter. Here, the position of the scroll bar can be specified in pixels. If the position is not specified, then this method will return the current position of the scroll bar. Hence, the following example shows how to implement the scrollLeft() method in jQuery. When the user goes to the right of the page and then clicks the button, then it will be taken to the left of the page.

jQuery scrollLeft() Method Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
      html, body{
      width: 300%;
      }
    </style>
    <title>Document</title>
  </head>
  
  <body style="background-color: lavender;">
    <h2>jQuery - Scroll Left</h2>
    <hr>
    <br><br>
    <div style="position: fixed; background-color:darkcyan; padding: 0.75%;">
      <p>Click the button to scroll to left of the page.</p>
      <button>ScrollLeft</button>
    </div>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('button').click(function(){
            $(document).scrollLeft('0');
        })
    });    
  </script>
</html>

Output:

Example 1: jQuery scrollLeft() Method


All jQuery Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.