Build a scroll progress bar with vanilla js & CSS3 Property in 2 minutes or less

Nilay Vishwakarma
1 min readJun 7, 2018

--

HTML:

A simple placeholder for progress bar

<div id="_progress"></div>

CSS:

Use var to access a CSS Property ‘ — scroll’. ‘ — scroll’ stores the scroll percentage for the page.

#_progress {
--scroll: 0%;
background: linear-gradient(to right,rgb(0, 143, 105) var(--scroll),transparent 0);
position: fixed;
width: 100%;
height: 5px;
top:0px;
z-index: 100;
}

JS:

On scroll calculate value of ‘ — scroll’ css property.

document.addEventListener(
"scroll",
function() {
var scrollTop =
document.documentElement["scrollTop"] || document.body["scrollTop"];
var scrollBottom =
(document.documentElement["scrollHeight"] ||
document.body["scrollHeight"]) - document.documentElement.clientHeight;
scrollPercent = scrollTop / scrollBottom * 100 + "%";
document
.getElementById("_progress")
.style.setProperty("--scroll", scrollPercent);
},
{ passive: true }
);

Live:

If you enjoyed the post, please clap so others discover it. Cheers.

--

--