How to Get Horizontal Scroll Position Using jQuery
In web development, tracking user scroll behavior is essential for creating dynamic user interfaces, custom parallax effects, and horizontal navigation systems. This article demonstrates how to easily retrieve the horizontal scroll position of the browser window or any scrollable container using jQuery's built-in methods. You will learn the exact syntax required, how to read position values dynamically during a scroll event, and how to apply these techniques to specific HTML elements.
Using the scrollLeft()
Method
The primary tool for getting the horizontal scroll position in jQuery
is the .scrollLeft() method. This method returns the
horizontal position of the scroll bar in pixels for the first matched
element, representing the number of pixels currently hidden from view to
the left of the scrollable area.
Getting Window Scroll Position
To find out how far the entire webpage has been scrolled
horizontally, apply .scrollLeft() to the
window object:
let horizontalPosition = $(window).scrollLeft();
console.log("Current horizontal scroll position: " + horizontalPosition + "px");If the page is aligned all the way to the left, this method returns
0. As the user scrolls horizontally to the right, the
returned pixel value increases.
Getting the Scroll Position of a Specific Element
If you have an overflow-x: auto or
overflow-x: scroll container (such as a
<div>), you can target that specific element using
its selector:
let containerScroll = $('#scrollable-container').scrollLeft();
console.log("Container scroll position: " + containerScroll + "px");Tracking Horizontal Scroll Dynamically
To detect and respond to horizontal scroll changes in real time, pair
the .scrollLeft() method with jQuery's
.on('scroll') event listener.
$(window).on('scroll', function() {
let currentX = $(this).scrollLeft();
console.log("Horizontal position: " + currentX);
});For a specific scrollable element:
$('#scrollable-container').on('scroll', function() {
let currentX = $(this).scrollLeft();
// Example: Trigger an action when scrolled past 200px
if (currentX > 200) {
console.log("Scrolled past 200px horizontally");
}
});Setting the Horizontal Scroll Position
The .scrollLeft() method can also be used as a setter.
By passing a numeric parameter, you can programmatically move the
scrollbar to a specific horizontal coordinate:
// Scrolls the window 500 pixels from the left edge
$(window).scrollLeft(500);
// Resets a container back to the beginning
$('#scrollable-container').scrollLeft(0);