How to detected when user's stop scrolling - Angular 5

Viewed 3351

I'm trying to hide a div when user scroll the page, and when stop scroll I want to show the div.

I'm using @HostListener but it fired only user scroll the page.

  @HostListener('window:scroll', ['$event']) 
  onScroll(event) {
    this.scroll = true;
    setTimeout(() => {
      this.scroll = false;
    }, 2000);
  }
3 Answers

To improve your current code, call clearTimeout when the scroll event is detected. It will prevent the div from showing up until you stop scrolling for the specified amount of time.

public scroll = false;
private timeout: number;

@HostListener('window:scroll', ['$event'])
onScroll(event) {
  this.scroll = true;
  clearTimeout(this.timeout);
  this.timeout = setTimeout(() => {
    this.scroll = false;
  }, 300);
}

See this stackblitz for a demo.

Related