How to detect if browser window is scrolled to bottom?

I need to detect if a user is scrolled to the bottom of a page. If they are at the bottom of the page, when I add new content to the bottom, I will automatically scroll them to the new bottom. If they are not at the bottom, they are reading previous content higher on the page, so I don't want to auto-scroll them since they want to stay where they are.

How can I detect if a user is scrolled to the bottom of the page or if they have scrolled higher on the page?


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.