Determines the JS code at the bottom of the scroll bar

  • 2020-03-26 23:05:41
  • OfStack

To determine the bottom of the scroll bar, three DOM attribute values are needed, namely scrollTop, clientHeight, and scrollHeight.

ScrollTop is the scrolling distance of the scrollbar on the Y-axis.

ClientHeight is the height of the visible area of the content.

ScrollHeight is the height of the visual area of the content plus the overflow distance.

As can be seen from the introduction of these three attributes, the bottom condition of the scrollbar is scrollTop + clientHeight == scrollHeight.

Don't say much nonsense, hurry up the code (compatible with different browsers).


 


//The length of the scroll bar on the Y axis
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!");
  }
};

It's even easier to implement with jquery,

$(window).scroll(function(){
  var scrollTop = $(this).scrollTop();
  var scrollHeight = $(document).height();
  var windowHeight = $(this).height();
  if(scrollTop + windowHeight == scrollHeight){
    alert("you are in the bottom");
  }
});

If you want to determine whether the scroll bar in a certain element is bottom or not, according to a similar idea, you can replace the document.body with a specific element. The way to get scrollTop and scrollHeight is the same, but to get the visible height of an element, you need to use the offsetHeight attribute, and you can directly follow the gourd.


Related articles: