While scrolling a webpage, we can use JavaScript to get the scroll position of the top of the window using the scrollTop property.

document.documentElement.scrollTop

The scrollTop property will return the top position of the element it is called on. In this case, we use it on the webpage document we are on 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.

Note this can also be done in jQuery using the scrollTop() method.

Using JavaScript to Get 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 onscroll event on the window object to launch a function while we scroll the page. Every time the function is called, we will use the scrollTop property on the document object to get the top position of our page.

Finally, we will use the textContent property to display the number as we scroll.

Here is the code:

window.onscroll = function() {
  document.getElementById("scroll-number").textContent = (document.documentElement.scrollTop);
  //The code below is to make sure the #scrolling-div stays in view of the user as they scroll
  if (document.documentElement.scrollTop > document.getElementById("div1").offsetTop && document.documentElement.scrollTop < (document.getElementById("div1").offsetTop + 4000)){
    document.getElementById("scrolling-div").style.position = "fixed";
  } else {
     document.getElementById("scrolling-div").style.position = "absolute";
  }
};

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 use JavaScript to get the scroll position.

Categorized in:

JavaScript,

Last Update: February 26, 2024