Preventing mouse emulation events (i.e. click) from touch events in Mobile Safari / iPhone using Javascript

Jaime Cham picture Jaime Cham · May 23, 2010 · Viewed 20.4k times · Source

In doing a single page Javascript app with interactive DOM elements I've found that the "mouseover-mousemove-mousedown-mouseup-click" sequence happens all in a bunch after the "touchstart-touchmove-touchend" sequence of events.

I've also found that it is possible to prevent the "mouse*-click" events from happening by doing an "event.preventDefault()" during the touchstart event, but only then, and not during the touchmove and touchend. This is a strange design, because because it is not possible to know during the touchstart yet whether the user intents to drag or swipe or just tap/click on the item.

I ended up setting up a "ignore_next_click" flag somewhere tied to a timestamp, but this is obviously not very clean.

Does anybody know of a better way of doing this, or are we missing something?

Note that while a "click" can be recognized as a "touchstart-touchend" sequence (ie no "touchmove"), there are certain things, such as keyboard input focus, that can only happen during a proper click event.

Answer

Finesse picture Finesse · Apr 15, 2019

Just prevent the touchend event. It will let the browser scroll the page when you touch the element but won't let it emit artificial mouse events.

element.addEventListener('touchend', event => {
  event.preventDefault();
});