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 find left position of element in horizontal scroll container using jQuery?
To find the left position of element in horizontal scroll container using jQuery, use the offset() function combined with scrollLeft(). The offset() method returns the coordinates of an element relative to the document, while scrollLeft() gets or sets the horizontal scroll position.
The key is to calculate the left offset by subtracting the container's left offset from the element's left offset, then adding the current scroll position of the container.
Example
You can try to run the following code to learn how to find left position of an element in horizontal scroll container ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var scrollArea = $('#box');
var toScroll = $('#box .myclass');
function myScroll() {
toScroll.each(function() {
var self = $(this);
$(this).css('cursor', 'pointer');
$(this).on('click', function () {
var leftOffset = self.offset().left - scrollArea.offset().left + scrollArea.scrollLeft();
scrollArea.animate({ scrollLeft: leftOffset });
alert('Left position: ' + leftOffset + 'px');
});
});
}
myScroll();
});
</script>
<style>
#box {
width: 250px;
height: 300px;
margin-left: 20px;
border: 1px solid black;
overflow-x: scroll;
white-space: nowrap;
}
.myclass {
width: 250px;
height: 100px;
margin: 35px;
display: inline-block;
background: linear-gradient(to right, red, blue);
}
</style>
</head>
<body>
<p>Click on any element to find its left position in the scroll container.</p>
<div id="box">
<div class="myclass">First (Click Me)</div>
<div class="myclass">Second (Click Me)</div>
<div class="myclass">Third (Click Me)</div>
</div>
</body>
</html>
When you click on any element, the code calculates its left position within the scroll container and displays it in an alert. The container will also animate to scroll to that position.
Conclusion
Finding the left position of an element in a horizontal scroll container requires combining jQuery's offset() method with the container's scrollLeft() value to get accurate positioning coordinates relative to the scrollable area.
