2 min read

Touch Events

Touch Events provide a low-level interface for interpreting finger activity on touch screens or trackpads. While Pointer Events are generally recommended for cross-device compatibility, understanding Touch Events is still useful for legacy support or specific touch-only interactions.

1. Event Types

  • touchstart: Fired when a touch point is placed on the touch surface.
  • touchmove: Fired when a touch point is moved along the touch surface.
  • touchend: Fired when a touch point is removed from the touch surface.
  • touchcancel: Fired when a touch point has been disrupted (e.g., by a system alert or too many touch points).

2. The Touch Lists

Unlike mouse events which track a single cursor, touch events must track multiple fingers. The event object contains three lists of Touch objects:

  1. touches: A list of all touch points currently on the screen.
  2. targetTouches: A list of touch points on the target element that originated the event.
  3. changedTouches: A list of touch points that caused the current event (e.g., the finger that just lifted off in touchend).

3. Basic Usage

const box = document.querySelector('.box');

box.addEventListener('touchstart', (e) => {
  e.preventDefault(); // Prevent default browser behavior (scrolling, zooming)
  console.log('Touch started');
  console.log('Number of touches:', e.touches.length);
});

box.addEventListener('touchmove', (e) => {
  const touch = e.changedTouches[0];
  console.log(`Moved to: ${touch.pageX}, ${touch.pageY}`);
});

box.addEventListener('touchend', (e) => {
  console.log('Touch ended');
});

4. Handling Gestures

Since Touch Events are low-level, you have to manually calculate gestures like "swipe" or "pinch".

Example: Detect Swipe Left/Right

let startX = 0;
let endX = 0;

document.addEventListener('touchstart', e => {
  startX = e.changedTouches[0].screenX;
});

document.addEventListener('touchend', e => {
  endX = e.changedTouches[0].screenX;
  handleGesture();
});

function handleGesture() {
  if (endX < startX) console.log('Swiped Left');
  if (endX > startX) console.log('Swiped Right');
}

programming/javascript/vanilla/javascript programming/javascript/vanilla/events programming/javascript/vanilla/pointer-events