Search code examples
javascriptpercentagecalculation

How can I calculate an elements scroll position as a percentage?


I would like to calculate the scroll position of an element within the window as a percentage.

  • 0% is where the top of the element is at the bottom of the window (it has not been shown yet)
  • 100% is where the bottom of the element is at the top of the window (all of the element has been shown)

I am close, but I know I'm thinking about something in my math wrong. I've put together a little demo to show the scroll percentage for multiple elements, but the percents 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>


Solution

  • Just like you've pointed out, I think you have something wrong with the math at these lines:

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

    Try changing those lines with this:

    const scrollableDistance = window.innerHeight + rect.height;
    const scrolled = window.innerHeight - rect.top;
    
    const pct = (scrolled / scrollableDistance) * 100;
    

    Let me know if this solves your problem so I can suggest something else.