Reputation: 2307
How can you check if the scroll bar is positioned at the bottom? Using JQuery or JavaScript
Upvotes: 19
Views: 32649
Reputation: 1704
This should work without any additional library:
const elem = document.querySelector(".container");
Math.abs(elem.scrollHeight - elem.clientHeight - elem.scrollTop) <= 1;
scrollTop
is a non-rounded number, whilescrollHeight
andclientHeight
are rounded — so the only way to determine if the scroll area is scrolled to the bottom is by seeing if the scroll amount is close enough to some threshold (in this example, that should be 1).
Reference: Scroll height
Upvotes: 0
Reputation: 106
This is working well for my chat window. It also detects if the content isn't long enough to be scrolled.
function atBottom(ele) {
var sh = ele.scrollHeight;
var st = ele.scrollTop;
var ht = ele.offsetHeight;
if (ht == 0) {
return true;
}
return st == sh - ht;
}
Update: Someone suggested this edit for a cleaner version of the same code. I like my more verbose version as an answer, but its a good idea to have both available.
function atBottom(el) {
let sh = el.scrollHeight,
st = el.scrollTop,
ht = el.offsetHeight;
return ht == 0 || st == sh - ht;
}
Upvotes: 8
Reputation: 880
This worked for me (using jQuery):
$(document).ready(function(){
$('div').scroll(function(){
//scrollTop refers to the top of the scroll position, which will be scrollHeight - offsetHeight
if(this.scrollTop == (this.scrollHeight - this.offsetHeight)) {
console.log("Top of the bottom reached!");
}
});
});
Taken from here.
Upvotes: 4
Reputation: 69905
You can check if the element scrollTop
is equal to the element innerHeight
.
if($('div').scrollTop() == $('div').innerHeight()){
//Reached the bottom
}
Upvotes: 1
Reputation: 13672
You find the height of the scrolling container, then compare that to the scroll position. If they are the same, then you have reached the bottom.
<div style="overflow: auto; height: 500px">
</div>
$(document).ready(function()
{
$('div').scroll(function()
{
var div = $(this);
if (div.height() == div.scrollTop() + 1) //scrollTop is 0 based
{
alert('Reached the bottom!");
}
});
});
Edit: a little testing in a js fiddle and I realized the previous version is incorrect. You can use a DOM property to find out how much scrolling there is a perform a little math with the height of the element like so
var div = $(this);
if (div[0].scrollHeight - div.scrollTop() == div.height())
{
alert('Reached the bottom!');
}
Upvotes: 17