Search code examples
javascriptangularscroll

Angular specific way to determine scrolling direction


Is there any angular specific way to determine if a user is scrolling upwards or downwards? I came across solutions which all were either about jQuery or pure JavaScript. I tried below JSFiddle but not getting it right, it always shows scrolling up.

JSFiddle Demo

Here's how I tried it:

this.currentPosition = window.pageYOffset;

onContentScrolled(e) {
    let scroll = window.pageYOffset;
    if (scroll > this.currentPosition) {
      console.log('scrollDown');
    } else {
      console.log('scrollUp');
    }
    this.currentPosition = scroll;
}

The fiddle works all fine. But I want to know the correct way to implement in angular component.

It only outputs "scrollUp" every time. Can anyone tell me what I am doing wrong here. I think it's with the global currentPosition variable but don't know how to proceed further.


Solution

  • Maybe I have lot more complex structure in my app, which includes dynamic content from various components, so I tried below and it worked seamlessly!

    private scrollChangeCallback: () => void;
    currentPosition: any;
    startPosition: number;
    
    ngAfterViewInit() {
      this.scrollChangeCallback = () => this.onContentScrolled(event);
      window.addEventListener('scroll', this.scrollChangeCallback, true);
    }
    
     onContentScrolled(e) {
      this.startPosition = e.srcElement.scrollTop;
      let scroll = e.srcElement.scrollTop;
      if (scroll > this.currentPosition) {
        this.showButton = false;
      } else {
        this.showButton = true;
      }
      this.currentPosition = scroll;
    }
    
    ngOnDestroy() {
      window.removeEventListener('scroll', this.scrollChangeCallback, true);
    }
    

    e.srcElement works like a charm!

    And thanks for all solutions above! They weren't wrong just didn't fit to my app