iamsubingyawali
iamsubingyawali

Reputation: 393

Detecting end of scroll in a div

I have a dynamic website with many blog posts. I want to load just four posts at first and load another four when scrolled to end. I know how to handle it on the backend, but I am having problem on the frontend. I have set the height of html and body to 100%, due to which scroll events on the window didn't work. As a workaround, I decided to use a single div to detect the scroll. I added scroll event on the div, and it worked fine. But when I tried to detect the end of scroll on the div, the code executed at the beginning of the page load before performing any scrolls. The code I used is:

if (element.scrollHeight - element.scrollTop === element.clientHeight){
   alert("End");
}

How do I make the alert to appear only after the div has been scrolled to the end instead at the begining?

Upvotes: 8

Views: 32163

Answers (4)

dimchikpc
dimchikpc

Reputation: 1

element.scrollTopMax has poor browser support, try this

Math.abs(element.scrollHeight - element.clientHeight - element.scrollTop) <= 1

Upvotes: 0

Luca Meneghini
Luca Meneghini

Reputation: 21

element.scrollTop + element.offsetHeight >= element.scrollTopMax

I mainly use this as a condition

Upvotes: 2

Anil kumar
Anil kumar

Reputation: 1628

Answer for year 2023.
Now we have scrollend event.
Tested on chromium 108, firefox 109

Example:

const output = document.querySelector("p#output");

document.addEventListener("scrollend", (event) => {
  output.innerHTML = `Document scrollend event fired!`;
});

According to mdn docs:
The scrollend event fires when the document view has completed scrolling.
Scrolling is considered completed when the scroll position has no more pending updates and
the user has completed their gesture.

Know more at mdn : Document: scrollend event

Upvotes: 1

Cybershadow
Cybershadow

Reputation: 1167

You can use element.scrollTop + element.offsetHeight>= element.scrollHeight to detect scroll end.

Update: Also adding a condition so that it won't fire when scrolling upwards. For more on upward scroll condition,you can check this link.

const element = document.getElementById('element');
let lastScrollTop = 0;
element.onscroll = (e)=>{
if (element.scrollTop < lastScrollTop){
      // upscroll 
      return;
   } 
   lastScrollTop = element.scrollTop <= 0 ? 0 : element.scrollTop;
    if (element.scrollTop + element.offsetHeight>= element.scrollHeight ){
       console.log("End");
    }
}
#element{
  background:red;
  max-height:300px;
  overflow:scroll;
}
.item{
height:100px;
}
<div id="element">
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
</div>

Upvotes: 14

Related Questions