Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to set scroll left position in jQuery?
The scrollLeft() method in jQuery allows you to get or set the horizontal scroll position of an element. When you pass a value to this method, it sets the scroll position from the left edge of the element.
Syntax
To set the scroll left position, use the following syntax ?
$(selector).scrollLeft(position)
Where position is the number of pixels to scroll from the left edge.
Basic Example
Here's a simple example that demonstrates how to set the scroll left position ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
#scrollable {
width: 200px;
height: 100px;
overflow: auto;
border: 1px solid #ccc;
}
#content {
width: 500px;
height: 50px;
background: linear-gradient(to right, red, blue, green, yellow);
}
</style>
</head>
<body>
<div id="scrollable">
<div id="content">This is a wide content that can be scrolled horizontally</div>
</div>
<button onclick="scrollTo100()">Scroll to 100px</button>
<button onclick="scrollTo200()">Scroll to 200px</button>
<script>
function scrollTo100() {
$('#scrollable').scrollLeft(100);
}
function scrollTo200() {
$('#scrollable').scrollLeft(200);
}
</script>
</body>
</html>
Animated Scrolling
You can also animate the scroll position using the animate() method ?
$('#scrollable').animate({
scrollLeft: 150
}, 1000);
Getting Current Scroll Position
To get the current scroll left position without setting it, call the method without parameters ?
var currentPosition = $('#scrollable').scrollLeft();
console.log('Current scroll position: ' + currentPosition);
Conclusion
The scrollLeft() method in jQuery provides an easy way to control horizontal scrolling of elements, either by setting a specific position or retrieving the current scroll offset.
