Detecting weather user scrolls the bottom of the div or not in react js and javascript

Viewed 113

I want to implement infinite scrolling in the table, so I am calculating div height in one possible way, you can see below

 let fixedCh = e.target.clientHeight;
 let calCh = e.target.scrollHeight - e.target.scrollTop;
 if (fixedCh === calCh) {
      alert('load more');
    }

In this approach,calCh is varied from different resolutions. Is there any other way of doing this, so that it can work through all kind of browser and screen resolution

1 Answers

Your approach is good; you need to call your function initially when the user loads the page to check if the user's screen resolution is already to the end of the scroll, call "alert('load more')".

The problem is that for some users, based on their screen, the scrollbar will not be visible to scroll, so your event of scroll won't check the element. To fix this, as I said above, you need to initially load your screen check function when the "Dom is ready".

Here is the basic implementation:

function loadMore (e) {
  let fixedCh = e.clientHeight;
  let calCh = e.scrollHeight - e.scrollTop;
  if (fixedCh === calCh) {
    alert('load more');
  }
}

// listen on scroll and check target element fixedCh === calCh
function listenOnScroll() {
  document.getElementById('app').addEventListener('scroll', (e) => {
    loadMore(e.target)
  })
},


window.onload = (event) => {
  loadMore(document.getElementById('app').target)
};

I will call the function "loadMore" when the dom is ready or loaded and pass the targetted Dom element.

Later, I'll call the "listenOnScroll" function to listen on the target element scroll and then call the "loadMore" function from it.

Related