The scrollLeft() method in JQuery is used to get and set the position of the Horizontal scrollbar of an HTML element.
Say, you want to get the exact position of the cursor when <p> element is horizontally scrolled.
And the scrollLeft() method helps us to achieve that.
Also it helps us to set the horizontal scroll cursor position.
Let us see how scrollLeft() method acts as a getter method.
<html> <head> <title> My First Programme </title> <script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script> </head> <body> <h1> JQuery </h1> <p style = "width: 100px; overflow:auto"> Scroll right and <br/> left to see the <br/> change <br/> https://www.google.com <br/> <br/> </p> <button> Click Here </button> <script> $('button').click( function() { alert($('p').scrollLeft()); }); </script> </body> </html>
So, if we look at the above code, we have a <p> element.
<p style = "width: 100px; overflow:auto"> Scroll right and <br/> left to see the <br/> change <br/> https://www.google.com <br/> <br/> </p>
And we have a <button> element,
<button> Click Here </button>
And on button click, the JQuery statement gets triggered,
$('button').click( function() { alert($('p').scrollLeft()); });
So, what we have done is, invoked the scrollLeft() method on the <p> element.
$('p').scrollLeft()
And an alert is generated,
alert($('p').scrollLeft());
Now, you need to move the contents of the <p> element right or left(Well! They are scrollable).
<p style = "width: 100px; overflow:auto"> Scroll right and <br/> left to see the <br/> change <br/> https://www.google.com <br/> <br/> </p>
And then click on the button, you can see the value in the alert changes.
This is because the scrollLeft() method captures the position of the cursor when the contents of the <p> element is moved horizontally.
<html> <head> <title> My First Programme </title> <script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script> </head> <body> <h1> JQuery </h1> <p style = "width: 120px; overflow:auto"> Click on the <br/> below button <br/> to set cursor <br/> position at 30px <br/> https://www.google.com <br/> <br/> </p> <button> Click Here </button> <script> $('button').click( function() { $('p').scrollLeft(30); }); </script> </body> </html>
So, if we look at the above code, we have a <p> element.
<p style = "width: 120px; overflow:auto"> Click on the <br/> below button <br/> to set cursor <br/> position at 30px <br/> https://www.google.com <br/> <br/> </p>
And we have a <button> element,
<button> Click Here </button>
And on button click, the JQuery statement gets triggered,
$('button').click( function() { $('p').scrollLeft(30); });
So, what we have done is, invoked the scrollLeft() method on the <p> element.
$('p').scrollLeft(30);