#AD 50 Projects In 50 Days (HTML, CSS & JavaScript) - Sharpen your skills by building 50 mini projects!

Create a reading progress indicator (on scroll) in JavaScript

By Michael Burrows | Last modified August 28th 2020 | GitHub Source Code [GitHub]

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>
Code language: HTML, XML (xml)

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; }
Code language: CSS (css)

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");
Code language: JavaScript (javascript)

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 + "%"; };
Code language: JavaScript (javascript)

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); }
Code language: JavaScript (javascript)

Related Posts