Problem
I have an image slider, and the issue is, that the click event on a preview image is fired after dragging. I showcased it in this video
Supposed Behavior
The click event should only be triggered when the user did not drag beforehand.
Code
isGrabbing: boolean = false;
startX: number;
startXPerc: number;
translateX: number = 0;
diffPerc: number;
@ViewChild('slider') slider;
onMouseDown(e: MouseEvent): void {
const pageX = e.pageX;
this.isGrabbing = true;
this.startX = pageX - this.slider.nativeElement.offsetLeft;
this.startXPerc = this.translateX;
}
onMouseUp(e: MouseEvent): void {
this.isGrabbing = false;
}
onMouseMove(pageX: number): void {
if (!this.isGrabbing) return;
const x = pageX - this.slider.nativeElement.offsetLeft;
const diff = this.startX - x;
this.diffPerc = 100 * diff / this.slider.nativeElement.offsetWidth;
this.translateX = this.startXPerc - this.diffPerc;
}
get translateXValue(): string {
return `translateX(${this.translateX}%)`
}
onSmallItemClick(i: number): void {
// this line should only be triggered
// if the user did not drag beforehand
this.animate(i * -100);
}
Html:
<div
class="small-slider-container"
(mousedown)="onMouseDown($event)"
(mousemove)="onMouseMove($event)"
(mouseup)="onMouseUp($event)"
#slider
>
<div
class="small-slider"
[style.transform]="smallTranslateXValue"
[class.grabbing]="smallSliderGrabbing"
[class.grab]="!smallSliderGrabbing"
>
<div
class="item"
*ngFor="let i of images; let j = index"
[style.left]="j * 10 + '%'"
(click)="onSmallItemClick(j)"
>
<div class="content">
<img src="{{ i }}">
</div>
</div>
</div>
</div>
click is triggered after mouseup . Your onMouseUp
function needs to be combined with onSmallItemClick
.
At the moment, mousedown happens and sets isGrabbing
to true, then mouseup sets it to false. So, by the time click fires the user is 'not' grabbing.
From w3.org :
The sequence of these events is:
mousedown mouseup click
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.