Day 15: Scroll Progress Indicator
Build a scroll progress indicator that calculates how far down the page the user has scrolled and updates a progress bar in real time.
JavaScript focus
- reading current scroll position
- measuring document height vs viewport height
- basic math for percentage calculation
- updating a visual element based on derived state
- listening to the scroll event
Nice extras
- make the bar fixed to the top of the viewport
- animate width changes smoothly with CSS
- keep the indicator visible but subtle
- use a CSS custom property instead of inline width if you want a cleaner styling hook
- add a percentage label if you want a more obvious visual
- reset correctly when the user returns to the top
- only initialize if the progress element exists
MDN prep
Scroll Progress Indicator
- Scroll progress indicator appears at top of page on scroll.
The HTML
<!-- put this last in the <header> -->
<div aria-hidden="true" class="progress_indicator">
<div class="progress_scroll"></div>
</div>
The JavaScript
function initScrollProgressBar() {
const docElement = document.documentElement;
const root = document.querySelector(".progress_indicator");
if (!root) return;
// scroll width
const scroll = root.querySelector(".progress_scroll");
// listen for the scroll
document.addEventListener("scroll", () => {
// document height
const docHeight = docElement.scrollHeight;
const viewHeight = window.innerHeight;
// calculations
const scrollTop = window.scrollY;
const scrollableDistance = docHeight - viewHeight;
const progress = scrollTop / scrollableDistance;
const progressPercent = progress * 100;
scroll.style.width = `${progressPercent}%`;
});
}
initScrollProgressBar();