Get the scroll position of a web page in the browser window using JavaScript

By Faruque Ahamed Mollick

We may be needed the scroll position of a web page in the browser window. So here in this tutorial, we are going to see how to get the scrolling position amount of a web page on the browser window every time a user scrolls the window.

Now we are going to see the JavaScript code which will return the scroll position from the top. JavaScript has the scroll event listener which we can use to detect the scroll.

Below is how JavaScript event listener code can be called:

window.addEventListener("scroll", function(){
   // Your code goes here
});

Now, to get the scroll position value we will use scrollY property which will return the distance from the top of the element.

Run JavaScript code or call a function after n seconds

Validating phone numbers in JavaScript

Here we are going to create a div element and make it fixed position so that we can see the scroll position of our web page. Below is our HTML code:

<p id="scroll_position"></p>
<div style="height: 3000px;"></div>

And below is the CSS:

#scroll_position {
  position: fixed;
  top: 0;
  right: 0;
  background: #777;
  color: #fff;
  padding: 8px;
  width: 100px;
}

Now we can see that our div element always in top right position so that we can always see it even after we scroll down. Here we will show the scroll position so that we can always see the position value.

Now, we are going to put our code inside the event listener that we kept blank:

window.addEventListener("scroll", function(){
    var scroll = window.scrollY;
    document.getElementById("scroll_position").textContent=scroll;
});

Complete code that will show the scrolling position

Below is the complete code:

<!DOCTYPE html>
<html>
<head>
  <title></title>

  <style type="text/css">
    #scroll_position {
      position: fixed;
      top: 0;
      right: 0;
      background: #777;
      color: #fff;
      padding: 8px;
      width: 100px;
    }
  </style>
</head>
<body>


<p id="scroll_position"></p>
<div style="height: 3000px;"></div>


<script type="text/javascript">

window.addEventListener("scroll", function(){
    var scroll = window.scrollY;
    document.getElementById("scroll_position").textContent=scroll;
});

</script>
</body>
</html>

If you create an HTML file and paste the above code and after that run the HTML file on your browser, you will be able to see the scrolling position after you start scrolling the page on your browser. With the change of scrolling position, we will also see the change of the value on top right position.

 

Leave a Reply

Your email address will not be published. Required fields are marked *