I'm trying to make a progress scrollbar that shows what percent of the "wrapper" element has been scrolled but am not getting it fully working. Here's the site structure:
body
div#scrollFix
div#fauxBody
header#top
div#wrapper
footer
Here's my code so far:
{
const scrollFix = document.getElementById("scrollFix");
const fauxBody = document.getElementById("fauxBody");
fauxBody.__make("div", {id: "progress-bar", placement : "afterbegin"});
const getScrollPercentage = () => {
const wrapper = document.getElementById("wrapper");
const wrapperHeight = wrapper.offsetHeight;
const wrapperTop = wrapper.getBoundingClientRect().top;
const windowHeight = window.innerHeight;
const scrollPosition = scrollFix.scrollTop;
// If the wrapper element is not in view, return 0%
if (wrapperTop > windowHeight || wrapperTop + wrapperHeight < 0) {
return 0;
}
// Calculate the percentage scrolled from the top of the wrapper element
const scrolledFromTop = scrollPosition - wrapperTop;
const scrollPercentage = (scrolledFromTop / wrapperHeight) * 100;
// Return the percentage as a number rounded to 2 decimal places
return Number(scrollPercentage.toFixed(2));
}
scrollFix.addEventListener("scroll", () => {
const width = getScrollPercentage();
const progressBarEl = document.getElementById("progress-bar");
progressBarEl.style.width = `${width}%`;
});
}
Any ideas?