Mister_L
Mister_L

Reputation: 2611

angular check if scroll was triggered manually or from script

I'm working with Angular 7, and I have a directive that listens to the scrolling of an element. The problem is, that I want the directive to respond only to manual scrolls, and ignore programmatic scrolls done with element.scrollTop = x. The directive contains a scroll listener, like so:

@HostListener('scroll', ['$event'])
  onScroll($event) {
  }

In one of the places in my code I set a programmatic scrollTop as described above, and an event was caught by the listener. I tried to find a property on $event that would indicate whether the event was manual or not, but couldn't find one. Did I miss it? Or perhaps that I can somehow trigger a custom event in vanilla javascript that would contain such indication (I know that in jQuery you can do that, but I'm not using jQuery here...). Thanks.

Upvotes: 1

Views: 958

Answers (1)

Arif
Arif

Reputation: 1645

Just add a flag and set it to false before you manual scroll.

Don't forget to set the flag back to true in your scroll handler

private handleScroll = true;

@HostListener('scroll', ['$event'])
onScroll($event) {
  if (!this.handleScroll) {
    this.handleScroll = true;
    return;
  }
}

public manualScroller() {
  this.handleScroll = false;

  this.element.scrollTop = 100;
}

Upvotes: 2

Related Questions