How to create a scroll progressbar

Let’s learn how we can create a scroll progress bar and add it to a website. We can add this pretty easily to any type of website either it’s a static website or if you are using a CMS like WordPress.

Designing The Progress Bar

Designing the progress bar is pretty straight forward. We need one div for the progress bar container (something light color) and another div with highlighted color.

<div class="scroll-bar-container">
<div id="scrollBarHighlight" class="scroll-bar-highlight"></div>
</div>

The next step will be to add CSS and see our design.

.scroll-bar-container {
    position: fixed;
    width: 100%;
    background-color: #f1f1f1;
    height: 4px;
    z-index:100;
}
.scroll-bar-highlight {
    background-color: #3e3eff;
    height: inherit;
    width:0%;
}

Ok, the CSS part is also very simple, we have the container div with a fixed position and a height of 4px. The progress bar has a different color and width of 0%. We will control this from javascript based on the scroll position.

Now The Fun Part!

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

//This function will run when scrolled
function renderProgressBar() {
  //select the progress bar by its ID
  var progressBar = document.getElementById("scrollBarHighlight");
  
  //get current scroll height
  var currScrollHeight = document.documentElement.scrollTop;
  
  //get total content height and screen height
  var totalContentHeight = document.documentElement.scrollHeight; 
  var screenHeight= document.documentElement.clientHeight;

  //Total scroll height
  var totalScrollHeight = totalContentHeight - screenHeight;

  //Scrolled position percentage
  var scrolled = (currScrollHeight / totalScrollHeight ) * 100;
  //Change the progress bar width
  progressBar.style.width = scrolled + "%";
}

Let’s go through the above code. First, we are adding a scroll event listener and passing a function renderProgressBar(). Now each time we will scroll the page this renderProgressBar() function will run.

Here you can find list of all the properties we can use. https://developer.mozilla.org/en-US/docs/Web/API/Element

We need to get the currScrollHeight, totalContentHeight, screenHeight . Now we can get the total screen height by subtracting screenHeight from totalContentHeight

Next we need to get the percentage of scroll, if we do (currScrollHeight / totalScrollHeight) it will return number between 0-1 but we need it in between 0-100, So we can just simply multiply by 100 and we will get the percent.

Now we are almost done, we can now just change our progressBar width based on our scrolled percentage and we e are done🥳.

Thank you for reading this post. Stay safe and spread kindness. 🙂

One Response

Leave a Reply to Lynn Creger Cancel reply

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