Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 499
Jaime Cham Avatar asked May 23 '10 06:05

Jaime Cham


People also ask

Does Safari support touch events?

Safari mobile doesn't support touch events.

Does Touchstart work on desktop?

onTouchStart works only for mobile. Also, this event goes before the onClick event.

What is the use of Touch_move?

Definition and Usage The touchmove event occurs when the user moves the finger across the screen. The touchmove event will be triggered once for each movement, and will continue to be triggered until the finger is released. Note: The touchmove event will only work on devices with a touch screen.

What are Javascript mouse events?

The MouseEvent interface represents events that occur due to the user interacting with a pointing device (such as a mouse). Common events using this interface include click , dblclick , mouseup , mousedown . MouseEvent derives from UIEvent , which in turn derives from Event . Though the MouseEvent.


1 Answers

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(); }); 
like image 151
Finesse Avatar answered Sep 19 '22 13:09

Finesse