Reputation: 75
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
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
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
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';
}
}
Upvotes: 0