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

Create a reading progress indicator (on scroll) in JavaScript

Last modified August 13th 2024 | GitHub Source Code [GitHub] | #js

Reading progress indicators are generally used on long form articles and web pages to provide a visual clue indicating how far from the end of an article a user has scrolled. In this tutorial we’ll be creating a reading progress indicator that’ll look 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 reading progress functionality with JavaScript. First we’ll need to declare a variable for the actual 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 using an event scroll listener:

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

That’s it for this tutorial. For your reference the full working 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