alexanderstanchev
alexanderstanchev

Reputation: 75

How to fire only once Mousewheel scroll

I am trying on scroll with mousewheel to do some actions. I want no matter how fast or how many times you scroll the wheel, it to count as "one". Now if you scroll fast it will count more times.

https://stackblitz.com/edit/angular-yttk3y

Upvotes: 0

Views: 332

Answers (3)

Narayanan Ramanathan
Narayanan Ramanathan

Reputation: 1400

Have a timer to restrict the scroll for certain duration and retain the scroll direction to detect change in scroll direction.

import { Directive, HostListener } from '@angular/core';
import { timer } from 'rxjs';
@Directive({
  selector: '[appMouseScroll]'
})
export class MouseScrollDirective {
  Ttimer;
  isMouseWheelInRogress;
  scrollUp;

  @HostListener('wheel', ['$event']) onMouseScroll(e) {

    if (!this.isMouseWheelInRogress || (!this.scrollUp && e.deltaY < 0 || this.scrollUp && e.deltaY > 0)) {
      if (this.Ttimer) {
        this.Ttimer.unsubscribe();
      }
      this.Ttimer = timer(500).subscribe(() => {
        this.isMouseWheelInRogress = false;
      });

      if (e.deltaY < 0) {
        this.scrollUp = true;
        console.log('scrolling up');
      } else if (e.deltaY > 0) {
        this.scrollUp = false;
        console.log('scrolling down');
      }
    }
    this.isMouseWheelInRogress = true;
  }
}

Upvotes: 1

Arayik
Arayik

Reputation: 144

You need to have a timeout function there in order to avoid all the scroll events and only fire the last event.

Here is example. https://angular-pwnp9p.stackblitz.io

Upvotes: 0

jitender
jitender

Reputation: 10429

Save scroll direction and use it in if condition something like

scrollDirection:'up'|'down';
   @HostListener('wheel', ['$event']) onMouseScroll(e) {
    if (e.deltaY < 0 && this.scrollDirection !='up') {
      console.log('scrolling up');
      this.scrollDirection='up';
    } else if (e.deltaY > 0 && this.scrollDirection !='down') {
      console.log('scrolling down');
      this.scrollDirection='down';
    }
  }

demo

Upvotes: 0

Related Questions