DEV Community

Michael Burrows
Michael Burrows

Posted on • Updated on • Originally published at w3collective.com

Create a reading progress indicator (on scroll) in JavaScript

Reading progress indicators are generally used on long form articles.

They provide a visual clue for readers indicating how far they are from the end of an article.

Alt Text

Let’s get started by adding the basic markup for the progress bar to our HTML.

<div id="progress-bar"></div>
Enter fullscreen mode Exit fullscreen mode

Next the CSS.

The transition makes the changing of the width appear smoother, you may prefer it without.

#progress-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 0;
  height: 4px;
  z-index: 99;
  background-color: #b22222;
  transition: width 1s;
}
Enter fullscreen mode Exit fullscreen mode

With the HTML and CSS in place we can start to build the functionality with JavaScript.

First we define our progress bar element.

const progressBar = document.getElementById("progress-bar");
Enter fullscreen mode Exit fullscreen mode

Next we add a function to detect how far a user has scrolled and set the progress bar width accordingly.

const setProgressBar = () => {
  let scrollDist = document.documentElement.scrollTop || document.body.scrollTop;
  let progressWidth = (scrollDist / (document.body.scrollHeight - document.documentElement.clientHeight)) * 100;
  progressBar.style.width = progressWidth + "%";
};
Enter fullscreen mode Exit fullscreen mode

Last we check if the page contains a progress bar.

If it does then we call the setProgressBar function when the user scrolls the browser.

if (progressBar) {
  window.addEventListener("scroll", setProgressBar);  
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)