While scrolling a webpage, we can use jQuery to get the scroll position of the top of the window using the scrollTop() method.
$(window).scrollTop();
The scrollTop() method will return the top position of the element it is called on. In this case, we use it on the window object so it will return the top position of the screen. If we have not scrolled at all, it will return 0, since that means we are at the top of the page.
Getting the Scroll Position While Scrolling a Webpage
In this example, we will get and show the current scroll position as we scroll this page. To make sure this page is large enough to have to scroll on, we will create a very tall div. Here is the html:
The scrollTop position is:
We will use the jQuery scroll() method on the window object to launch a function while we scroll the page. Every time the function is called, we will use the scrollTop() method on the window object again to get the top position of the window.
Finally, we will use the jQuery text() method to display the number as we scroll.
Here is the code:
$(window).scroll(function(){
$("#scroll-number").text($(window).scrollTop());
//The code below is to make sure the #scrolling-div stays in view of the user as they scroll
if ($(window).scrollTop() > $("#div1").position().top && $(window).scrollTop() < ($("#div1").position().top + 4000)){
$("#scrolling-div").css("position","fixed");
} else {
$("#scrolling-div").css("position","absolute");
}
});
The final code and output for this example is below:
Code Output:
Full Code:
The scrollTop position is:
Hopefully this article has helped you understand how to get the scroll position using jQuery.