#Check if user has scrolled near the bottom of the page using directive

2 messages · Page 1 of 1 (latest)

cedar scaffold
#

The problem with my code is that once the user has reached near the bottom of the page, what I do want it to do is being called multiple times, but it needs to be called only once. I cannot understand whyy. Here's the following code:

@Directive({
  selector: '[appInfiniteScroll]'
})
export class InfiniteScrollDirective 
  constructor() { }

  @HostListener('window:scroll', ['$event'])
  onInfiniteScroll = (event: any) => {
    const windowWidth = window.innerWidth;

    // Check if user is mobile ( 1024px );
    if (windowWidth <= 1024) {

      // Logic to check if user has scrolled near the bottom of the page ( near 300px from bottom );
      if (document.body.scrollHeight - (window.innerHeight + window.scrollY) <= 300) {

        console.log('This console.log and the following code is being called multiple times and I can not understand whyyyyy!!??');

// Anything I put here is called multiple times, like 6, 7, 8 or even 15 times
      }
    }
  }

}
unborn kiln
#

The JavsScript window.scroll event is not a "one and done" type of event. It will keep firing repeatedly while a user is scrolling. You need to either use the scrollend event, or throttle the scroll events.

https://developer.mozilla.org/en-US/docs/Web/API/Document/scroll_event#examples

The scroll event fires when the document view has been scrolled.
To detect when scrolling has completed, see the Document: scrollend event.
For element scrolling, see Element: scroll event.