2

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?

M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
iamsubingyawali
  • 193
  • 1
  • 2
  • 15

3 Answers3

8

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>
Cybershadow
  • 1,097
  • 9
  • 16
1

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

Anil kumar
  • 1,216
  • 4
  • 12
0
element.scrollTop + element.offsetHeight >= element.scrollTopMax

I mainly use this as a condition