I want to calculate the scroll position of the element within the window as a percentage.
I'm close, but I know I'm thinking something wrong in the math. I made a small demo to show the scroll percentage for multiple elements, but the percentages are all wrong.
function getElemScrollPercent(selector){ const scale = 0.1; const el = document.querySelector(selector); const out = el.querySelector('.out'); function calc(){ const rect = el.getBoundingClientRect(); //don't bother calculating if it's off screen if (rect.top < window.innerHeight && rect.bottom > 0) { const total = (window.scrollY) / (rect.bottom + rect.height); const pct = total * 100; out.innerHTML = `${Math.round(pct)}%`; } } window.addEventListener('scroll', calc); calc(); } getElemScrollPercent('#one'); getElemScrollPercent('#two'); getElemScrollPercent('#three');
* { box-sizing: border-box; } body { display: flex; flex-direction: column; min-height: 400vh } section { height: 100vh; position: relative; border: 1px solid black; } #one { background:#d1b4b4; } #two { background:#b4d1bc; } #three { background:#b4b5d1; } .out { position: sticky; top: 0; display: inline-block; padding: .5rem; background: #CCC; }
<section id="one"> <span class='out'>%</span> </section> <section id="two"> <span class='out'>%</span> </section> <section id="three"> <span class='out'>%</span> </section>
As you pointed out, I think there's something wrong with your math in these lines:
Try changing these lines with:
Please tell me if this solves your problem so I can make other suggestions.