Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to create a page scroll indicator



We can easily understand how much a page on a web browser is scrolled using the position of the scroll bar. Imagine a custom scroll indicator, which can place anywhere on the page and style as we wish.

We can use the javascript window class onscroll method to grab the position of the scroll bar and use it to build our custom indicator.

Steps to build the scroll indicator

Step 1

Create an HTML mark-up. In this mark-up, a <div> envelopes everything. Inside <div> we can find an <h2> tag and another <div>.

This other <div> will serve as the indicator bar. Each of these tags is the given class name to be used in styling. Our markup can look like this:

<div class="overall">
  <h3>Scroll Position Indicator Bar</h3>
  <div class="container">
    <div class="progress" id="progBar"></div>


Next will be the styles.

Step 2

Style the markup that was just created. We style major elements of interest, like the progress bar, the overall div, and more. The style below is part of the complete style included in the code snippet later.

.overall {
  position: fixed;
  top: 0;
  z-index: 1;
  width: 100%;
  background-color: #f1f1f1;
container {
  width: 100%;
  height: 10px;
  background: #ccc;

  height: 10px;
  background: #04AA6D;
  width: 0%;

Now, add the JavaScript in the code.

Step 3

Write a JavaScript code to get the position of the scrollbar on the page. And give us a value through a simple computation, which we’ll use to manipulate the width of the progress bar in the styles. Our script can look like:

window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  var elementScroll = document.body.scrollTop || document.documentElement.scrollTop;
  var windowHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
  var scrollPos = (elementScroll / windowHeight) * 100;
  document.getElementById("progBar").style.width = scrollPos + "%";


Let’s look at the code below:


  • Line 3: The window.scroll event is targeted and the function scrollFunction is attached to it.
  • Lines 5 to 10: We contain the scrollFunction. Inside this function, the scroll details like the client browser window size and the position of the scrolling at any point are captured. It is used to get the percentage of the scroll page that is passed at any time. With this, the style of progBar is manipulated to reflect the position on the screen.



View all Courses

Keep Exploring