Kazunari
Kazunari

Reputation: 278

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

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);
  }

Upvotes: 3

Views: 4721

Answers (3)

A.Winnen
A.Winnen

Reputation: 1698

You can use RxJs's debouncetime for this usecase.

fromEvent(window, "scroll").pipe(
    tap(() => this.scroll = true),
    debounceTime(100)
).subscribe(() => {
    this.scroll = false;
});

Stackblitz example: https://stackblitz.com/edit/angular-dumymv

Upvotes: 4

Martin Parenteau
Martin Parenteau

Reputation: 73761

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.

Upvotes: 7

Keenan Diggs
Keenan Diggs

Reputation: 2342

Your approach works. And this Stackblitz proves it: https://stackblitz.com/edit/angular-5xcm6h

You may have an error somewhere else.

Upvotes: 0

Related Questions