devmark / angular-slick-carousel

Angular directive for slick-carousel
http://devmark.github.io/angular-slick-carousel/
MIT License
353 stars 125 forks source link

Item in array with a (click) event fired on "mouse up" #143

Open arcio opened 6 years ago

arcio commented 6 years ago

If I drag the carousel left <> right, when I mouse up, it fires a (click) event to the object in the array.

<ngx-slick class="carousel" #slickModal="slick-modal" [config]="slideConfig" width="100%">
  <div *ngFor="let story of stories | async; let i = index" ngxSlickItem class='slide' width="100%">
    <feature-story class="story-type-a" [title]="story?.headline" [storyID]="story?.$key" [handle]="story?.handle" [avatar]="story?.avatar"
      [date]="story?.timestamp" [storyImage]="story?.image" [bgColor]="story?.bgColor" [category]="story?.category"></feature-story>
  </div>
</ngx-slick>

feature-story itself has a click handler (click)="GoToStory(storyID)"

Is there a simple way to disable this? It doesn't appear to be happening on mobile, only with the mouse/trackpad.

joscmw95 commented 6 years ago

This is due to the way navigation is handled in Angular. Despite a drag, Angular still thinks that it is a mouse click hence triggering the event.

One of the ways to work around this situation is to use a timer on the mousedown event and assume that any (mousedown -> mouseup) that happens in a specified interval is a click:

// fires on mousedown, "(mousedown)=trackMouse()"
trackMouse() {
  this.mouseDown = true;
  window.setTimeout(() => {
    this.mouseDown = false;
  }, 100);
}

// fires on click, "(click)=navigateIfClick(item)"
navigateIfClick(item) {
  if (this.mouseDown) {
    this.router.navigate(['/item/', item.id]);
  }
}

A better solution could be tracking the position of the mousedown and mouseup event and assume it is a click if both events' positions are close.

trackMouseDown(event: MouseEvent) {
  this.x1 = event.x;
  this.y1 = event.y;
}

trackMouseUp(event: MouseEvent, item: Item) {
  let a = this.x1 - event.x;
  let b = this.y1 - event.y;
  let c = Math.sqrt(a * a + b * b);

  if (c < 10) {
    switch (event.which) {
      case 1:
        // left click
        this.router.navigate(['/items/', item.id]);
        break;
      case 2:
        // middle button
        window.open(window.location.hostname + `/items/${item.id}`, '_blank');
        break;
      case 3:
        // right click
        break;
      default:
        this.router.navigate(['/items/', item.id]);
        break;
    }
  }
}
arcio commented 6 years ago

Thanks! This worked like a charm, with one exception. I had to use an event listener as the function isn't always passed through from the component. document.getElementById("ID_NAME").addEventListener("mousedown", function(e) {self.FUNCTION_NAME(e);});