How to get the full size of the scroll?

Asked

Viewed 1,114 times

-1

I’m looking to acquire the percentage that my scroll is, to manipulate css. But I have these two variables:

document.documentElement.scrollTop; document.documentElement.scrollHeight;

The first one gives me the position of the scroll, and the second one gives me the size of the scroll. Closed, now I just need to split pos/height to have the percentage of scroll, but in what I realized the variable document.documentElement.scrollTop; when my scroll is at the end, it does not give the same value as document.documentElement.scrollHeight;, ie my percentage will never reach 100% if I use this calculation.

From what I understand the document.documentElement.scrollTop; does not arrive at the end in fact because the position is only caught at the top of the screen. The one way I make that percentage better, like catch the real size of the scroll?

  • Like scrollTop marks the position at the top of the viewport, it will never reach 100%. For your calculation to work just adjust its total value, that is, its total value is the scroll size less the page size (that would be the largest position that scrollTop can have). It is a more mathematical problem than programming, the calculation would be: 100 * scroll_atual / (scroll_total - tamanho_tela)

  • I think this can help you https://answall.com/questions/312511/howto detect or detect

1 answer

3


I turned the comment into a response, so I can post an example.


Like scrollTop marks the position of the top of the viewport, will never reach 100%.

For your calculation to work just adjust its total value, that is, its total value is the scroll size minus the page size (that would be the largest position that scrollTop can have).

It is a problem more mathematical than programming, the calculation would be:

100 * scroll_atual / (scroll_total - tamanho_tela)

Example

let elem = document.getElementById('perc')
let doc = document.documentElement

window.addEventListener('scroll', function() {
    let value = parseInt(100 * doc.scrollTop / (doc.scrollHeight - doc.clientHeight))
    elem.innerHTML = value + '%'
})
body {
  height: 1000px;
  position: relative;
}

#perc {
  position: fixed;
  top: 10px;
  left: 10px;
  color: white;
  background-color: tomato;
  padding: 5px;
}
<span id="perc">0%</span>


Performance

Remembering that events like scroll and resize are fired many times per second. So you want to (or should want to) control how many times these events can be fired.

To better understand search about Throttle and debauch of events.

  • I even saved it to the favorites :D

  • 1

    Oops, what an honor! D

  • Now look at this one, without JS, just with CSS https://codepen.io/una/pen/bwrEpZ is not the same and has much to do with detecting scroll position itself, but it is very mass!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.