5

I have looked at multiple formulas for getting the window offset where when scrolled to the top the offset is 0 and when scrolled to the bottom the offset is the offsetHeight. None have worked. Some give 0 when at the top but not the right height when at the bottom and vise versa.

This is the closest I have gotten:

document.addEventListener('scroll', setBackgroundColor)

function setBackgroundColor() {
  let offset = (window.innerHeight + window.scrollY) / document.body.offsetHeight
  console.log(offset, window.innerHeight + window.scrollY, document.body.offsetHeight)
}
html,
body {
  margin: 0;
  padding: 0;
  height: 500vh;
}

The closest I have gotten to zero is 0.2, but the height works fine. What would the formula be for getting 0 and scrollHeight?

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
  • 1
    The [code here](https://stackoverflow.com/questions/2387136/cross-browser-method-to-determine-vertical-scroll-percentage-in-javascript) worked for me, but simplified to `let offset = window.scrollY/ (document.body.offsetHeight - window.innerHeight)` – George Jul 16 '18 at 15:02

2 Answers2

5

To achieve 0 in a division, you need to left side of the operator to be equal to 0 (0 divided by anything is always 0). In your case, it is always equal to something higher than 0 since you are doing an addition of a number always larger than 0 and another one that is >= than 0.

Try dividing the scroll position with the document height minus the window scroll:

document.addEventListener('scroll', setBackgroundColor)

function setBackgroundColor() {
  let offset = window.scrollY / (document.body.offsetHeight - window.innerHeight)
  console.log(offset, window.innerHeight + window.scrollY, document.body.offsetHeight)
}
html,
body {
  margin: 0;
  padding: 0;
  height: 500vh;
}
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
  • You still get more than 1 if the bottom of the page. – Programmer Jul 16 '18 at 15:15
  • Depends on the context, I agree with your answer that `document.body.scrollHeight` is better, but both can result in the same value and achieve the same thing. I use the OP formula in this context and the output must not be the same in every browser since in Firefox, it is always between 0 and 1. – Karl-André Gagnon Jul 17 '18 at 12:43
1

One slight difference from Karl-André Gagnon solution (because as I commented, it gets more than 1 in the bottom of the page). use document.body.scrollHeight instead of document.body.offsetHeight:

let offset = window.scrollY / (document.body.scrollHeight - window.innerHeight)
Programmer
  • 1,973
  • 1
  • 12
  • 20