A reading indicator needs one number that works at the top, halfway through, and at the bottom of a page. Progress is that normalized number: 0 at the start, 1 at the end, and a fraction between them. The same idea drives animations and controls. Once you have progress, you can turn it into a width, a percentage, or an intermediate property value. section 13.3.1 section 12.1.3 section 13.5
Calculate progress from the distance traveled, then map it to the result you need:
- For an animation, divide elapsed time by duration. Pass that progress through an easing function if the motion should speed up or slow down, then calculate the property value with start + (end - start) * easedProgress. section 12.1.3
- For a page, divide window.scrollY by document.documentElement.scrollHeight - window.innerHeight. If there is no scrollable distance, use 0 rather than dividing by zero. section 13.3.1
- For a slider, map drag progress to its value with minValue + progress * (maxValue - minValue). section 13.5
Check the numbers
If a page is 4,000 px tall and its viewport is 1,000 px tall, the maximum scroll is 3,000 px. At scrollY = 1,500 px, progress is 1,500 / 3,000 = 0.5, or 50%. The same fraction places a value halfway between 0 and 200: 0 + 0.5 * (200 - 0) = 100. section 13.4 section 12.1.3
const progressBar = document.getElementById('progress-bar');
function updateProgressBar() {
const scrollableHeight = document.documentElement.scrollHeight -
window.innerHeight;
let scrollProgress = 0;
if (scrollableHeight > 0) {
scrollProgress = window.scrollY / scrollableHeight; #1
}
progressBar.style.width = `${scrollProgress * 100}%`; #2
const hue = scrollProgress * 120; #3
progressBar.style.backgroundColor = `hsl(${hue}, 70%, 50%)`;
if (scrollProgress > 0.03) { #4
progressBar.textContent = `${Math.round(scrollProgress * 100)}%`;
} else {
progressBar.textContent = '';
}
}
window.addEventListener('scroll', updateProgressBar); #5
window.addEventListener('resize', updateProgressBar); #5
#5
updateProgressBar(); #5
The reading indicator calculates scroll progress once, then uses it for width, percentage text, and a red-to-green hue change. It also handles pages that cannot scroll. section 13.3.1
Progress and speed are not the same thing. In a CSS cubic Bézier timing function, the horizontal axis is time and the vertical axis is property progress; the curve’s slope determines how quickly progress changes. A gentle start gives ease-in motion, while a gentle finish gives ease-out motion. JavaScript easing functions make the same practical distinction by transforming linear progress before interpolation. section 11.1.4 section 12.1.3
