[MB]

Create a reading progress indicator (on scroll) in JavaScript

Last modified on August 28th 2020 GitHub [Source] CodePen [Demo]

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.

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

<div id="progress-bar"></div>

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; }

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");

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 + "%"; };

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); }