How to Build a Reading Progress Bar With CSS and JavaScript
// Reading Progress bar in Html, Css and Js
// Html Part
<div id="progress-bar"></div>
// Css Part
#progress-bar {
--scrollAmount: 0%;
background-image: linear-gradient(to right, #4facfe 0%, #00f2fe 100%);
width: var(--scrollAmount);
height: 4px;
position: fixed;
top: 0;
left: 0;
}
// JavaScript Part
let processScroll = () => {
let docElem = document.documentElement,
docBody = document.body,
scrollTop = docElem['scrollTop'] || docBody['scrollTop'], //browser support, docElem or docBody // the heigth we are on currently starting from top
scrollBottom = (docElem['scrollHeight'] || docBody['scrollHeight']) - window.innerHeight, // the heigth of the entire content
scrollPercent = scrollTop / scrollBottom *100 + '%';
console.log(parseInt(scrollPercent) + '%'+ ' = ' + scrollTop + ' / ' + scrollBottom)
document.getElementById('progress-bar').style.setProperty('--scrollAmount', scrollPercent)
}
document.addEventListener('scroll', processScroll)