⚠️ Note that this post hasn't been updated for at least a year and the information may be outdated, proceed with caution! (Last updated: April 18, 2022)
The code below can be used on your templates or pages to add a reading progress bar at the top of your page.
Create your progress bar
The reading progress bar can be added to a template or custom module using the following HTML snippet:
<div id="progress-wrapper" class="progress-wrapper">
<div id="progress-bar" class="progress-bar"></div>
</div>
Style your progress bar
You can add the CSS below to your stylesheet or custom module to add styling to the progress bar:
.progress-wrapper {
width: 100%;
height: 5px; /* Bar height */
background-color: #f9f9f7 ; /* Bar background colour */
position: -webkit-sticky;
position: sticky;
top: 0;
}
.progress-bar {
width: 0;
height: 5px; /* Bar height */
background-color: #fc8c7a; /* Bar progress colour */
}
Get it working
Adding the following snippet to the JavaScript file or custom module JS section should result in a working progress bar:
/* Declare your variables: the progress bar and the post container */
const progressWrapper = document.getElementById("progress-wrapper"),
progressBar = document.getElementById("progress-bar"),
container = document.getElementById("container"),
body = document.body;
/* Math stuff */
function setProgress() {
let start = container.getBoundingClientRect().top,
end = container.getBoundingClientRect().bottom,
height = container.getBoundingClientRect().height;
if (start > 0) {
let width = 0;
progressBar.style.width = width;
} else {
let width = Math.abs(start) / height * 100 + "%";
progressBar.style.width = width;
}
}
/* Trigger the function on scroll */
window.addEventListener('scroll', setProgress);
The "container" highlighted in bold above is the ID for the container where you'd like the progress bar to start and end. For example, add a DIV in your Blog Content module around the post and give it an ID "post-wrapper", then swap that out above.
Sample
Check it out on Codepen:
See the Pen Reading Progress Bar Within Container by Stephanie O'Gay Garcia (@stephanieogaygarcia) on CodePen.