简体   繁体   中英

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

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.

in the onScroll function you need to check if the scroll reached the end of most right scroll by

if (document.body.scrollWidth - document.body.scrollLeft === document.body.clientWidth) {
  // fetch some data
}

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

For example.

if (document.body.scrollWidth - document.body.scrollLeft >= (document.body.clientWidth - 100)) {
  // fetch some data
}

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM