#AD Top Online Web Development & Programming Courses | Udemy
Newsletter Screenshot

Create a reading progress indicator (on scroll) in JavaScript

Last modified February 9th 2021 | GitHub Source Code [GitHub] | #js

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. In this tutorial we’ll be creating a reading progress indicator that looks and function like the following:

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. By using a transition the progress bar appears slightly animated when it’s width changes. This is entirely optional and you may prefer how the progress bar behave without it:

#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 complete we can start to build the functionality with JavaScript. First we need to declare a variable for the progress bar element:

const progressBar = document.getElementById("progress-bar");Code language: JavaScript (javascript)

Next we add a setProgressBar function that detects how far a user has scrolled down a page and then sets the width of the progress bar 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’ll put a check in place to see if a progress bar exists in the current page. If it does exist then we call the setProgressBar function when the user scrolls:

if (progressBar) {
  window.addEventListener("scroll", setProgressBar);  
}Code language: JavaScript (javascript)

That’s it for this tutorial. For your reference the source code can be found on GitHub. If you enjoyed this tutorial be sure to check out some of our other practical web development tutorials. Thanks for reading 🙂

Related Posts

#AD Shop Web Developer T-Shirts