How to differentiate between mousedown and mousedrag

331 Views Asked by At

I am performing some actions on onMousedown event. But then they also get executed for drag as drag starts with mouse down.

How can I ensure that actions on mouse-down don't happen for mouse drag?

Note: I am using scalajs-react, though that must not matter.

1

There are 1 best solutions below

0
luiscla27 On

Mouse drag events trigger an event of DragEvent type, mouse down triggers only MouseEvent. You can differentiate both, by validating dataTransfer attribute, which is only present in DragEvent, like this:

function functionTriggeredOnMouseDownAndDrag(evt) {
    if (typeof evt.dataTransfer !== 'undefined') {
        // code for mouse drag
    } else {
        // code for other mouse events
    }
}

element.addEventListener('mousedown', functionTriggeredOnMouseDownAndDrag)
element.addEventListener('mousemove', functionTriggeredOnMouseDownAndDrag)