How can I determine if a div is scrolled to the bottom?

Solution 1:

You're pretty close using scrollTop == scrollHeight.

scrollTop refers to the top of the scroll position, which will be scrollHeight - offsetHeight

Your if statement should look like so (don't forget to use triple equals):

if( obj.scrollTop === (obj.scrollHeight - obj.offsetHeight))
{
}

Edit: Corrected my answer, was completely wrong

Solution 2:

In order to get the correct results when taking into account things such as the possibility of a border, horizontal scrollbar, and/or floating pixel count, you should use...

el.scrollHeight - el.scrollTop - el.clientHeight < 1

NOTE: You MUST use clientHeight instead of offsetHeight if you want to get the correct results. offsetHeight will give you correct results only when el doesn't have a border or horizontal scrollbar

Solution 3:

Little late to this party, but none of the above answers seem to work particularly well when...

  • Display scaling is applied to the OS for UHD displays
  • Scaling/zoom is applied to the browser

To accommodate for all eventualities, you will need to round up the calculated scroll position:

Math.ceil(element.scrollHeight - element.scrollTop) === element.clientHeight

Solution 4:

Returns true if an element is at the end of its scroll, false if it isn't.

element.scrollHeight - element.scrollTop === element.clientHeight

Mozilla Developer Network

Solution 5:

function difference(first,sec){
  return Math.abs(first-sec);
}

document.getElementById("myDIV").addEventListener("scroll", function() {
  var diff = difference((this.scrollTop+this.clientHeight),(this.scrollHeight));
   
   if(diff < 5) {
      alert('Scroll Ends Here');
    }
});
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
  height: 250px;
  width: 250px;
  overflow: none;
  overflow-y: auto;
}

#content {
  height: 800px;
  width: 2000px;
  background-color: coral;
}
</style>
</head>
<body>

<p>Scroll inside the div element to display the number of pixels the content of div is scrolled horizontally and vertically.</p>

<div id="myDIV">
  <div id="content">Scroll inside me!</div>
</div>

<p id="demo"></p>

</body>
</html>

No JQuery or Javascript Library and it works well.