Search code examples
javascripthtmlscrollscrollbarpercentage

Scroll percentage for a div using javascript


const rightSide = document.querySelector("#rightSide");

let scrollPercentage = () => {
  let h = document.documentElement;
  let st = h.scrollTop || document.body.scrollTop;
  let sh = h.scrollHeight || document.body.scrollHeight;
  let percent = st / (sh - h.clientHeight) * 100;
  console.log(percent);
}

rightSide.onscroll = scrollPercentage;
.right-side {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 90%;
  width: 90%;
  background-color: #eee;
  overflow-y: scroll;
}

.top-page {
  width: 100%;
  height: 100%;
  background-color: red;
}

.bot-page {
  width: 100%;
  height: 100%;
  background-color: yellow;
}
<div class="right-side" id="rightSide">
  <div id="top-page" class="top-page"></div>
  <div id="bot-page" class="bot-page"></div>
</div>

I'm making a website and I want to get the scroll percentage of a div. I've used Tyler Pott's video on YouTube https://youtu.be/-FJSedZAers and he does that to the whole page (using the body). And this is my code:

 const rightSide = document.querySelector("#rightSide")

  let scrollPercentage = () => {
    let h = document.documentElement;
    let st = h.scrollTop || document.body.scrollTop;
    let sh = h.scrollHeight || document.body.scrollHeight;

    let percent = st / (sh - h.clientHeight) * 100;
    console.log(percent);
  }

  rightSide.onscroll = scrollPercentage;

When I run this, the console just outputs "NaN" which is to be expected. I am not sure what I should do in order to transfer that code onto the divs. I've tried to use things like

  const topPage = document.querySelector("#top-page");

And then add topPage instead of the body in document.body.scrollTop etc. but that obviously doesn't work.

This is sort of what the HTML looks like, and the top page has a width and height of the rightSide div and the bottom page has the same width but a minimum height of the rightSide div.

 <div class="right-side" id="rightSide">
  <div id="top-page" class="top-page"></div>
  <div id="bot-page" class="bot-page"></div>
 </div>

Solution

  • Coming back to this I knew that I had to understand the values assigned to the variables in order to make the equation simpler.

    So, a quick search for documentElement led me to this answer:

    "documentElement returns the Element that is the root element of the document (for example, the element for HTML documents)"

    Then, I realised that maybe that is the issue and it was. I assigned rightSide to h and that's all that was needed.

    let h = rightSide;

    Not sure if this is fully correct, sometimes at the end of the scroll you can get 100.05 or more, but I didn't need the precise number. Hope this helps.