How to Detect Touch Devices in JavaScript

Reliable techniques for detecting touch capability in JavaScript, including navigator.maxTouchPoints, ontouchstart, PointerEvent API, and why User-Agent sniffing is unreliable.

Touch & Input

Detailed Explanation

Detecting Touch Capability

Detecting whether a device supports touch input is important for adapting UI interactions, but it is more nuanced than a simple boolean check.

Recommended Approach

function isTouchDevice() {
  return (
    'ontouchstart' in window ||
    navigator.maxTouchPoints > 0
  );
}

Individual Checks Explained

navigator.maxTouchPoints: Returns the maximum number of simultaneous touch points. Value of 0 means no touch support. This is the most reliable single check.

console.log(navigator.maxTouchPoints);
// Phone: 5 or 10
// Desktop (no touch): 0
// Surface Pro: 10

'ontouchstart' in window: Checks if the browser exposes touch events. Historically the most common check, but some non-touch browsers may expose this property.

TouchEvent constructor:

const hasTouchEvents = 'TouchEvent' in window;

PointerEvent API: Modern browsers expose PointerEvent which unifies mouse, touch, and pen input:

const hasPointerEvents = 'PointerEvent' in window;

Why Not Use User-Agent Sniffing?

User-Agent strings are:

  • Unreliable (browsers fake them for compatibility)
  • Cannot detect hybrid devices (laptops with touchscreens)
  • Deprecated in favor of Client Hints

The Hybrid Device Problem

A laptop with a touchscreen has both mouse (fine pointer) and touch (coarse pointer). The user might switch between them at any time. Instead of detecting touch once, design your UI to support both:

// Listen for both touch and mouse events
element.addEventListener('pointerdown', handleInput);
// Use CSS to adapt
// @media (pointer: coarse) { ... }

Best Practices

  1. Prefer CSS media queries (pointer, hover) over JavaScript detection
  2. Never assume touch = mobile or no-touch = desktop
  3. Always provide keyboard accessibility regardless of touch support
  4. Use the PointerEvent API for unified input handling

Use Case

Web developers building interactive applications (maps, drawing tools, games) need to detect touch capability to register the correct event listeners and adjust interaction patterns.

Try It — Screen Info Display

Open full tool