How can i detect that the user is in the middle of the viewport while user scrolls down?

435 Views Asked by At

I have big data. It needs to be showed in virtual scroll. I am making http request when the user comes to the end of the page, then i am making new requestt t oget the new 25 items and i am adding to the existing one. For that i am using


@HostListener("window:scroll", [])
  onWindowScroll() {
    if (this.isScrolledIntoView() && !this.showLazyLoadSpinner) {
      this.lazyLoadData();
    }
  }

isScrolledIntoView() {
    if($('#lazyLoadTrigger').offset()) {
      const docViewTop = $(window).scrollTop();
      const docViewBottom = docViewTop + $(window).height();

      const elemTop = $('#lazyLoadTrigger').offset().top;
      const elemBottom = elemTop + $('#lazyLoadTrigger').height();
      return ((elemBottom <= docViewBottom + 1) && (elemTop >= docViewTop));
    }
  }

when ((elemBottom <= docViewBottom + 1) && (elemTop >= docViewTop)); returns true that means that the user scrolled intul the end of the page and it comes to the end and i need to make http request to get new data and add it.

lazyLoadTrigger is the id from the last block in the HTML, after i show all items.

  <app-table-type1 tableDataFlow="auction" [tableData]="searchFilteredData" [type1Headers]="type1TableHeaders"
          [type2Headers]="type2TableHeaders" (linkClicked)="boldSelectedRow($event)" id="auctionMainTable"></app-table-type1>
 <div id="lazyLoadTrigger" style="height: 50px;">
          <div id="lazyLoadSpinner" class="text-center" *ngIf="showLazyLoadSpinner">
            <img class="loading-image" [src]="logo" alt="Loading...">
          </div>
        </div>

How can i detect now when the user is in the middle of the page, to make this http request, but not at the end ?

1

There are 1 best solutions below

2
On

The window.scroll event usually provides data with the current scroll position. I see in your code that your onWindowScroll function does not take any parameters. just add an event parameter to get more data about the scroll position. Like so:

HostListener("window:scroll", [])
onWindowScroll(event: any) {
  if (this.isScrolledIntoView() && !this.showLazyLoadSpinner) {
    console.log(event);
    this.lazyLoadData();
  }
}