How to calculate the percentage of an element's scroll position?
P粉786800174
P粉786800174 2024-04-03 19:55:00
0
1
631

I want to calculate the scroll position of the element within the window as a percentage.

  • 0% is where the top of the element is at the bottom of the window (not shown yet)
  • 100% is the position where the bottom of the element is at the top of the window (all elements are displayed)

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>

P粉786800174
P粉786800174

reply all(1)
P粉178132828

As you pointed out, I think there's something wrong with your math in these lines:

const total = (window.scrollY) / (rect.bottom + rect.height);
  const pct = total * 100;

Try changing these lines with:

const scrollableDistance = window.innerHeight + rect.height;
const scrolled = window.innerHeight - rect.top;

const pct = (scrolled / scrollableDistance) * 100;

Please tell me if this solves your problem so I can make other suggestions.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template