Javascript: How to detect if browser window is scrolled to bottom?

window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
        // you're at the bottom of the page
    }
};

See demo


Updated code for all major browsers support (include IE10 & IE11)

window.onscroll = function(ev) {
    if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
        alert("you're at the bottom of the page");
    }
};

The problem with the current accepted answer is that window.scrollY is not available in IE.

Here is a quote from mdn regarding scrollY:

For cross-browser compatibility, use window.pageYOffset instead of window.scrollY.

And a working snippet:

window.onscroll = function(ev) {
    if ((window.innerHeight + window.pageYOffset ) >= document.body.offsetHeight) {
        alert("you're at the bottom of the page");
    }
};
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>

Note for mac

Based on @Raphaël's comment, there was a problem in mac due to a small offset.
The following updated condition works:

(window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 2

I didn't have the chance to test it further, if someone can comment about this specific issue it will be great.


The accepted answer did not work for me. This did:

window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.scrollHeight) {
      // you're at the bottom of the page
      console.log("Bottom of page");
    }
};

If you're looking to support older browsers (IE9) use the alias window.pageYOffset which has slightly better support.

Tags:

Javascript