jQuery Introduction | Element Dimensions | Element Scroll Position .scrollLeft() .scrollTop()
Element Scroll Position
jQuery provides methods that make it easy to return and set the scroll position of a selected element.
| Method | Description |
|---|---|
| .scrollLeft() | Gets the horizontal scroll bar position of the first element in the selected set, or sets the horizontal scroll bar position of the selected element to the value passed as an argument. |
| .scrollTop() | Gets the vertical scroll bar position of the first element in the selected set, or sets the vertical scroll bar position of the selected element to the value passed as an argument. |
.scrollLeft() and .scrollTop() Methods
The .scrollLeft() method returns the current horizontal scroll bar position of the selected element, or sets the horizontal scroll bar position of that element. The .scrollTop() method returns the current vertical scroll bar position of the selected element, or sets the vertical scroll bar position of that element.
The following example returns the scroll bar position of the selected element.
$("button").on("click", function(){
var left = $(".box").scrollLeft();
var top = $(".box").scrollTop();
$("span").text("Left:" + left + ", Top" + top);
});
The following example sets the scroll bar position of the selected element.
$("button").on("click", function(){
$(".box").scrollLeft(70);
$(".box").scrollTop(20);
var left = $(".box").scrollLeft();
var top = $(".box").scrollTop();
$("span").text("Left:" + left + ", Top" + top);
});
Getting Scroll Bar Position Information in Real Time
You can use the .on('scroll', function(){...}) method to get scroll bar position information in real time.
The following example gets the scroll bar position information of the selected element in real time.
$(".box").on('scroll', function(){
var left = $(this).scrollLeft();
var top = $(this).scrollTop();
$("span").text("Left:" + left + ", Top" + top);
});