2 min read

The Golden Pattern for Handling Touch Input

If you’re writing JavaScript handlers for touchscreen input, don’t forget other users too.

In my opinion, this is the golden pattern today:

if ('onpointerdown' in window) {
// Bind to Pointer Events: `pointerdown`, `pointerup`, etc
else {
// Bind to mouse events: `mousedown`, `mouseup`, etc

if ('ontouchstart' in window) {
// Bind to Touch Events: `touchstart`, `touchend`, etc
// Bind to keyboard events: `keydown`, `keyup`, etc
// Bind to `click` events

Some notes:

I did miss something out: IE 10 uses ms- prefixes for pointer events, so you should check this beforehand:

var pointerPrefix = 'onmspointerdown' in window ? 'ms' : '';

if ('on' + pointerPrefix + 'pointerdown' in window) {
var pointerdown = pointerPrefix + 'pointerdown';
// etc

Browser support: