Search code examples
javascriptangularfunctiontriggersclick

Angular 10 - Not to trigger (click) function on dragging


I have a div with an openlayers map like this:

<div id="map" (click)="getInfo($event)" class="map"></div>

I use dragging with my mouse to navigate around the map, and every time I do that the getInfo function triggers. I just want it to trigger when I single click the map, not when I navigate.

Is it possible? Thanks!


Solution

  • I had the same problem detecting dragging vs clicking but didn't want to use timed events. If clicked too slow it considers dragging if dragged too quick it considers clicking.

    Instead, I used mouse positioning. If x,y position changes between mouse down and click (which is fired on mouse up) it's dragging, if not it's clicking.

    Pseudo code:

    <div (mousedown)="onMouseDown($event)" (click)="onClick($event)"></div>
    

    .ts file:

    mousePosition = {
      x: 0,
      y: 0
    };
    
    mouseDown($event: MouseEvent) {
      this.mousePosition.x = $event.screenX;
      this.mousePosition.y = $event.screenY;
    }
    
    onClick($event: PointerEvent) {
      if (
        this.mousePosition.x === $event.screenX &&
        this.mousePosition.y === $event.screenY
      ) {
        // Execute Click
      }
    }