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
?
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;
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With