Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get scroll percentage between 0 and 1 when scrolling

Tags:

javascript

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?

like image 773
Get Off My Lawn Avatar asked Jul 16 '18 14:07

Get Off My Lawn


Video Answer


2 Answers

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;
}
like image 128
Karl-André Gagnon Avatar answered Oct 16 '22 15:10

Karl-André Gagnon


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)
like image 25
Programmer Avatar answered Oct 16 '22 15:10

Programmer