Javascript: 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
}
};
看演示
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>
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");
}
};
链接地址: http://www.djcxy.com/p/83344.html