To determine whether the scroll bar reaches the bottom, you need to use three attribute values of the DOM, namely scrollTop, clientHeight, and scrollHeight.
scrollTop is the scrolling distance of the scroll bar on the Y axis.
clientHeight is the height of the content visible area.
ScrollHeight is the height of the content’s visible area plus the overflow (scrolling) distance.
As can be seen from the introduction of these three attributes, the condition for the scroll bar to reach the bottom is scrollTop clientHeight == scrollHeight.
Without further ado, let’s quickly upload the code (compatible with different browsers).
function getScrollTop(){
var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
if(document.body){
bodyScrollTop = document.body.scrollTop;
}
if(document.documentElement){
documentScrollTop = document.documentElement.scrollTop;
}
scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
return scrollTop;
}
//The total height of the document
function getScrollHeight(){
var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
if(document.body){
bodyScrollHeight = document.body.scrollHeight;
}
if(document.documentElement){
documentScrollHeight = document.documentElement.scrollHeight;
}
scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
return scrollHeight;
}
//The height of the browser viewport
function getWindowHeight(){
var windowHeight = 0;
if(document.compatMode == "CSS1Compat"){
windowHeight = document.documentElement.clientHeight;
}else{
windowHeight = document.body.clientHeight;
}
return windowHeight;
}
window.onscroll = function(){
if(getScrollTop() getWindowHeight() == getScrollHeight()){
alert("you are in the bottom!");
}
};