Alexander Kim
Alexander Kim

Reputation: 18382

Detect bottom of the document onscroll with JS

Having hard time detecting bottom of the document. Trying the following code:

let bottomOfWindow = document.documentElement.scrollTop + window.innerHeight === document.documentElement.offsetHeight

Then if it's true i'm firing my custom function. But it's never true, because it can't be 100% equal, because:

console.log(document.documentElement.scrollTop + window.innerHeight + ' and document height is ' + document.documentElement.offsetHeight)

often gives such results: "3197.199951171875 and document height is 3198" and as you can see it's not equal, so my function won't fire. Math.round() won't help in my case. Any advice?

Upvotes: 1

Views: 700

Answers (2)

Unmitigated
Unmitigated

Reputation: 89214

You can detect if the document is scrolled to the bottom like this:

if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
    //at the bottom of the page
}

Demo:

window.addEventListener('scroll', function(event) {
    if(window.pageYOffset==0){
      alert('At the top of the page');
    }
    if ((window.innerHeight + window.pageYOffset ) >= document.body.offsetHeight) {
        alert("At the bottom of the page.");
    }
});
html, body{
  height: 3000px;
}

On Macs, there is a problem with a small offset (about 1px), so we can modify the check to subtract 2 from the body's offsetHeight.

if(window.innerHeight + window.pageYOffset >= document.body.offsetHeight - 2){
//at the bottom of the page
}

Upvotes: 1

David Culbreth
David Culbreth

Reputation: 2776

Change your comparison:

let bottomOfWindow = document.documentElement.scrollTop + window.innerHeight > document.documentElement.offsetHeight -1;

Upvotes: 1

Related Questions