Home > OS >  how to call a function when user reaches the end of horizontal scrollbar in Angular 10?
how to call a function when user reaches the end of horizontal scrollbar in Angular 10?

Time:11-22

I've certains amounts of item in list within a horizontal scrollbar. I want to load more item via a function when user reaches the end of scrollbar. I've tried to implement it via (scroll)="onScroll()" but this function won't be called if scollbar can't be scollred further. So, how do I know about the end of an horizontal scollbar?

I've tried it via tracking how much distance, a scrollbar have crossed.

CodePudding user response:

in the onScroll function you need to check if the scroll reached at the end of bottom by

if (document.body.scrollHeight - document.body.scrollTop === document.body.clientHeight) {
  // fetch some data
}

I also suggest to fetch the data before scroll reached to the bottom with some pixels, to not make the user wait.

For example.

if (document.body.scrollHeight - document.body.scrollTop >= (document.body.clientHeight - 100)) {
  // fetch some data
}

CodePudding user response:

I strongly suggest you to use an IntersectionObserver in order to see when an item at the bottom of the page has entered the viewport. This is usually a best practice performance wise.

There are many articles out there for using angular directives in order to achieve this and reuse this code (e.g. https://blog.prototyp.digital/how-to-implement-intersection-observer-api-in-angular/), but if you have a quick win, you can just adapt an example from the official IntersectionObserver documentation: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

You can simply pass a callback function to the IntersectionObserver where you refetch new data.

  • Related