Posted 16 days ago. Visible to the public. Repeats.

Event order when clicking on touch devices

Touch devices have their own set of events like touchstart or touchmove. Because mobile browsers should also work with with web applications that were build for mouse devices, touch devices also fire classic mouse events like mousedown or click.

When a user follows a link on a touch device, the following events will be fired in sequence:

  • touchstart
  • touchend
  • mousemove
  • mousedown
  • mouseup
  • click

Canceling the event sequence

The sequence can be canceled by either

  1. dragging the finger after touchstart
  2. touching the element for a long time
  3. an JavaScript event handler calling event.preventDefault() on the touchstart event
  4. an JavaScript event handler calling event.preventDefault() on the touchend events

If the sequence is canceled, the subsequents mouse events will never fire. Only these events will fire:

  • touchstart
  • touchend

Caveats when canceling with JavaScript

When you call event.preventDefault() on the touchstart or touchend event, you can prevent the subsequent mouse events:

Copy
$('.elem').on('touchstart', (event) => { event.preventDefault() })

Note that an event handler bound to a parent element (here document) can not cancel the sequence:

Copy
$(document).on('touchstart', '.elem', (event) => { event.preventDefault() })

There seems to be an inconsistency with current (2018-04) Chrome versions, where an event handler bound to the document can cancel the sequence when it calls event.preventDefault() on an touchend event.

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Author of this card:

Avatar
Henning Koch
Last edit:
16 days ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev