javascripthtmlcssajax

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?


Solution

  • 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>