Touch & Gestures on the Web — Mobile

Pointer events (pointerdown, pointermove, pointerup, pointercancel) give each finger a pointerId, a position and a timeStamp; keep the fingers in a Map and…

Tonight the neighbourhood head is on night patrol with a phone running "Night Watch", the web app Bagas built: residents' reports, the village map, and photos. His thumb only wants to scroll the list of reports, but the app reads the movement as a swipe, and a report gets deleted. On the map, it is the page that refuses to scroll at all.

How does it misread him? The browser knows nothing about taps, swipes or pinches. It only sends raw events: where the finger lands, where it moves, for how long, and how many fingers at once. A touch gesture on the web is a pattern you read yourself from that series of pointer events, and your app decides which movement counts as what.

Pointer events: one API for fingers, mice and pens

Pointer events send the same events for a finger, a mouse and a stylus. Four of them matter:

Event When it is sent
pointerdown a finger touches down (or a mouse button is pressed)
pointermove the finger moves
pointerup the finger lifts
pointercancel the browser takes the gesture over, for a scroll for example, so no further events will come
const report = document.querySelector('#report-13');

report.addEventListener('pointerdown', (e) => {
  console.log(e.type, e.pointerId, e.pointerType, e.clientX, e.clientY, e.timeStamp);
  // for example: pointerdown 7 touch 152 301 8421.5
});

The older API, touch events (touchstart, touchmove, touchend, touchcancel), is for fingers only. One event can carry several fingers at once:

List What it holds
e.touches every finger currently on the screen
e.targetTouches the fingers that touched down on this element
e.changedTouches the fingers that changed in this event

Each finger in there has an identifier. In touchend, the finger that just lifted is no longer in e.touches; look for it in e.changedTouches. For new code, use pointer events: every modern browser supports them, and the code works for a mouse and a pen too.

Tracking each finger with a Map

A two-finger gesture needs each finger's position separately. Keep them in a Map keyed by pointerId:

const villageMap = document.querySelector('#village-map');
const fingers = new Map(); // pointerId -> { x, y }

villageMap.addEventListener('pointerdown', (e) => {
  villageMap.setPointerCapture(e.pointerId);
  fingers.set(e.pointerId, { x: e.clientX, y: e.clientY });
});

villageMap.addEventListener('pointermove', (e) => {
  if (!fingers.has(e.pointerId)) return; // a mouse just passing over
  fingers.set(e.pointerId, { x: e.clientX, y: e.clientY });
});

function release(e) {
  fingers.delete(e.pointerId);
}
villageMap.addEventListener('pointerup', release);
villageMap.addEventListener('pointercancel', release);

Tap, long-press, swipe: three numbers

One-finger gestures are told apart by three numbers: how long the touch lasted, how far the finger moved from where it started, and in which direction. The usual thresholds, and the ones the Touch Guide game uses:

Gesture Its condition
tap never moved more than 10px, and lifted in under 300ms
long-press never moved more than 10px, and held for 500ms or more
swipe under 500ms, and moved at least 50px along the dominant axis

Before you go on, guess with that table. The neighbourhood head holds his thumb on one report for 400ms without moving, then lifts it. Is that a tap or a long-press?

Neither. 400ms without moving is too long for a tap and too short for a long-press. The gap from 300 to 500ms is left empty on purpose, so a hesitant touch neither opens the report nor brings up the menu.

"Never moved" means it is checked on every pointermove, not just at the end. A thumb that slides 14px and comes back to where it started is not a tap.

The direction of a swipe comes from the axis that moved more:

function swipeDirection(dx, dy) {
  if (Math.abs(dx) > Math.abs(dy)) return dx > 0 ? 'swipe-right' : 'swipe-left';
  return dy > 0 ? 'swipe-down' : 'swipe-up'; // y grows downwards
}

console.log(swipeDirection(-160, 6)); // swipe-left
console.log(swipeDirection(60, 90));  // swipe-down: |dy| is larger

dx and dy are the position at pointerup minus the position at pointerdown.

Pinch: the distance between two fingers

A pinch is two fingers moving towards or away from each other. What you compute is a ratio of the distance between the two fingers: the distance at the end divided by the distance when the second finger touched down.

function twoFingerDistance(fingers) {
  const [a, b] = [...fingers.values()];
  return Math.hypot(a.x - b.x, a.y - b.y);
}

The neighbourhood head puts two fingers on the map 60px apart, then spreads them to 150px. The ratio is 150 / 60 = 2.5. The thresholds:

A ratio is used, not a difference in px, so a pinch reads the same on a small phone and a big tablet.

touch-action: sharing the work with the browser

When a finger touches down, the browser decides first: does it handle this gesture itself (scroll, zoom), or hand it to your code? The CSS property touch-action decides:

.photo-carousel { touch-action: pan-y; }  /* up-down scrolling still works, left-right swipes are yours */
#village-map { touch-action: none; }   /* panning and pinching on the map, all handled by your code */
.button { touch-action: manipulation; } /* scrolling and zoom stay, without double-tap zoom */
Value What the browser still handles
auto everything (the default)
pan-x, pan-y scrolling on one axis only
pinch-zoom two-finger zoom
manipulation scrolling and pinch zoom, without double-tap zoom
none nothing

When the browser takes over, you get pointercancel and no more pointermove. So a carousel left on auto "sticks" halfway through a swipe: the browser starts scrolling, and your swipe is cancelled.

Passive listeners

A touchstart or touchmove listener may call e.preventDefault() to cancel the scroll, so the browser has to wait for that listener to finish before it scrolls. So that scrolling does not stutter, a listener can promise it will not cancel anything: { passive: true }.

// On window, document and body, touchstart and touchmove are passive out of the box.
document.addEventListener('touchmove', (e) => {
  e.preventDefault(); // ignored: the page still scrolls, and Chrome writes a warning in the console
});

const carousel = document.querySelector('.photo-carousel');
let isHorizontal = false; // set by your swipe recognizer
carousel.addEventListener('touchmove', (e) => {
  if (isHorizontal) e.preventDefault(); // takes effect, because this listener is passive: false
}, { passive: false });

In a passive listener, preventDefault() does nothing. If you really need to cancel the scroll, put the listener on the element itself with { passive: false }, and cancel only once your gesture is certain. Better still: set touch-action, because the browser reads it before the first event is sent.

Touch targets big enough

A thumb is bigger than a cursor. WCAG 2.2 criterion 2.5.8 (level AA) asks for targets of at least 24 x 24 CSS px, or spacing from other targets. That is the floor. Apple recommends 44 x 44 pt and Material Design 48 x 48 dp, and WCAG 2.5.5 (AAA) asks for 44 x 44 px. The icon's drawing may stay small; it is the touch area that grows:

.delete-icon {
  width: 24px;
  height: 24px;
  padding: 12px; /* a 48 x 48 px touch area */
  box-sizing: content-box;
}

Leave space between icons too. A delete icon pressed up against an edit icon still gets hit by mistake, even when each is 24px.

💡 The notch and the screen height

On phones with a notch or a home bar, content can be covered. Add viewport-fit=cover, then keep clear of the screen edges with env():

<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
.bottom-bar { padding-bottom: max(12px, env(safe-area-inset-bottom)); }
.full-screen { height: 100dvh; }

env(safe-area-inset-top), -right, -bottom and -left are the distances from the screen edge to the safe area; on a phone without a notch they are 0. For height, 100vh is measured with the browser's address bar hidden, so it can be taller than the visible screen. 100dvh follows the height currently visible, 100svh is always the smallest, and 100lvh always the largest.

💡 In React Native

In a React Native app, gestures are usually written with react-native-gesture-handler. The thresholds and the logic are the same, just wrapped up:

import { GestureDetector, usePinchGesture } from 'react-native-gesture-handler';

// Gesture Handler 3 (SDK 58), inside a component:
const pinch = usePinchGesture({
  runOnJS: true,
  onDeactivate: (e) => {
    console.log(e.scale > 1 ? 'pinch-out' : 'pinch-in'); // scale = end distance / start distance
  },
});

// <GestureDetector gesture={pinch}><VillageMap /></GestureDetector>

In Gesture Handler 2 (SDK 57 and older), it is a builder: Gesture.Pinch().runOnJS(true).onEnd(...). Version 3 still has the builder, but it is deprecated.

The next lesson, Animations (Reanimated), uses gestures like this to move the screen along with the finger.

⚠️ Stuck pinches, dead scrolling and mis-tapped icons

TL;DR: Pointer events (pointerdown, pointermove, pointerup, pointercancel) give each finger a pointerId, a position and a timeStamp; keep the fingers in a Map and remove them in pointerup and pointercancel. Tap: never moves more than 10px and lasts under 300ms. Long-press: does not move and lasts 500ms or more. Swipe: under 500ms and at least 50px along the dominant axis. Pinch: end distance divided by start distance, under 0.7 is pinch-in, over 1.3 is pinch-out. touch-action (pan-y, none, manipulation) decides which gestures stay with the browser. In a passive listener, preventDefault() is ignored. Touch targets are at least 24px (WCAG 2.5.8), better 44 to 48px. The notch: viewport-fit=cover and env(safe-area-inset-*); the screen height: 100dvh.

⚡ One API for every finger

Write:

report.addEventListener('pointerdown', (e) => {
  console.log(e.type, e.pointerId, e.pointerType, e.clientX, e.clientY, e.timeStamp);
});

Meaning: Pointer events send the same events for a finger, a mouse and a pen. Each finger has its own pointerId, so keep its position in a Map, and remove it in pointerup and in pointercancel too.

⚡ Tap, long-press or swipe

Guess first: the neighbourhood head holds his thumb on one report for 400ms without moving, then lifts it. Is that a tap or a long-press?

Neither. A tap must be under 300ms, a long-press at least 500ms. The gap from 300 to 500ms is left empty on purpose.

Meaning: Tap: never moves more than 10px and lasts under 300ms. Long-press: doesn't move and lasts 500ms or more. Swipe: under 500ms and at least 50px along the dominant axis.

⚡ An ignored preventDefault

Write:

document.addEventListener('touchmove', (e) => {
  e.preventDefault();
});
Guess first: this listener is added so the page won't scroll along. What happens when the neighbourhood head slides his thumb?

The page still scrolls. On window, document and body, touchmove listeners are passive out of the box, so preventDefault() is ignored.

Meaning: Use touch-action, for example pan-y on a carousel: up-and-down scrolling stays with the browser, left-and-right swipes belong to your code.

What you will learn