Skip to content

how to get difference between window height and scroll location?

I want to make custom infinite scroll, so when I try this

 const scrollPosition = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
if(window.innerHeight-scrollPosition >100){
console.log("end")
}

but it does not work.

Answer

If your wanting to know when your 100 pixels away from the end, then you can get the current element scrollHeight and subtract the parent elements height and then subtract your extra 100.

Now compare this to the parentElements scrollTop, if it’s greater then your scrollbar is within this 100px section..

Example below.. If you scroll down until your within 100 pixels of the end, the background will change silver.

document.body.innerText =
  new Array(400).fill('Scroll me down, ').join('');

window.addEventListener('scroll', (e) => {
  const body = document.body;
  const parent = body.parentElement;
  const pixelsFromBottom = 
    body.scrollHeight -
    parent.clientHeight
    -100;
  body.classList.toggle('inf'
    ,parent.scrollTop > pixelsFromBottom);
});
.inf {
  background-color: silver;
}

This will work not with just Body, but also any sub controls too, below I’ve created a header footer, with and a scrollable region.

const scroller = document.querySelector('main');
const target = document.querySelector('.content');

target.innerText =
  new Array(400).fill('Scroll me down, ').join('');

scroller.addEventListener('scroll', (e) => {
  const body = target;
  const parent = body.parentElement;   
  const pixelsFromBottom = 
    body.scrollHeight -
    parent.clientHeight
    -100;
  parent.classList.toggle('inf'
    ,parent.scrollTop > pixelsFromBottom);
});
html, body {
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
  background-color: cyan;
  overflow: hidden;
}

body {
  display: flex;
  flex-direction: column;
}

main {
  position: relative;
  flex: auto;
  overflow-y: scroll;
  background-color: white;
}

.content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.inf {
  background-color: silver;
}
<header>This is a header</header>
<main><div class="content">main</div></main>
<footer>This is the footer</footer>