Mohan Ravi
Mohan Ravi

Reputation: 97

Why Javascript touchstart and mousedown events tiggered at same time?

Take a look at this fiddle: demo

I have attached two events to the div element first one is mousedown and second one is touchstart.

While clicking the element from the touch device both mousedown and touchstart is getting triggered, my expectation is only to trigger the respective events i.e only `touchstart needs to be triggered from the mobile device.

Upvotes: 2

Views: 6165

Answers (2)

Javad Masoudian
Javad Masoudian

Reputation: 62

I tested Jasmin's solution, but it did not work for me, so I handled it via setTimeout

let freezed = false;
let counter = 1;

const onPress = () => {
  if(freezed) return;

  freezed = true;
  setTimeout(() => {
    freezed = false;
  }, 100);
  
  document.getElementById("counter").innerText = counter++
}

document.getElementById("button").addEventListener("touchstart", onPress);
document.getElementById("button").addEventListener("mousedown", onPress);
<button id="button">
 Mouse down or touch me
</button>

<p>Counter: <span id="counter">0</span></p>

Upvotes: -1

jasmin_makasana
jasmin_makasana

Reputation: 482

Please have a look at this fiddle

Normally the event order is : 1) touchstart 2) touchmove 3) touchend 4) mousemove 5) mousedown 6) mouseup 7) click

When any of touch event gets cancelled, then mouse event won't be called. Even if touch move occurs, then mouse event won't occur. Hope this helps :)

Upvotes: 6

Related Questions