While scrolling a webpage, we can use jQuery to get the scroll position of the top of the window using the scrollTop() method.


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:

  //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)){
  } else {

The final code and output for this example is below:

Code Output:

The scrollTop position is:

Full Code:

The scrollTop position is:

Hopefully this article has helped you understand how to get the scroll position using jQuery.

Categorized in:


Last Update: February 26, 2024