Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

isTouchDevice

Detects whether the current device supports touch events.

TypeScript
Copied!
1/**
2 * Detects whether the current device supports touch events.
3 *
4 * @returns True if the device supports touch input, false otherwise.
5 */
6export function isTouchDevice(): boolean {
7  return (
8    typeof window !== 'undefined' &&
9    ('ontouchstart' in window || navigator.maxTouchPoints > 0)
10  );
11}
  • Dual Detection Strategy

    Combines both ontouchstart property and navigator.maxTouchPoints for broader and more reliable touch support detection.

  • Safe for SSR Environments

    Checks for window existence to avoid runtime errors during server-side rendering.

  • Minimal and Efficient

    The implementation is concise, fast, and doesn't rely on external dependencies or heavy APIs.

  • Cross-Browser Compatibility

    Covers older mobile browsers (ontouchstart) and modern desktop touchscreens (maxTouchPoints).

Tests | Examples

TypeScript
Copied!
1const originalWindow = global.window;
2const originalNavigator = global.navigator;
3
4afterEach(() => {
5  global.window = originalWindow;
6  global.navigator = originalNavigator;
7});
8
9test('returns true when ontouchstart exists in window', () => {
10  // @ts-ignore
11  global.window = { ontouchstart: () => {} };
12  expect(isTouchDevice()).toBe(true);
13});
14
15test('returns true when maxTouchPoints > 0', () => {
16  // @ts-ignore
17  global.window = {};
18  // @ts-ignore
19  global.navigator = { maxTouchPoints: 2 };
20  expect(isTouchDevice()).toBe(true);
21});
22
23test('returns false when no touch support', () => {
24  // @ts-ignore
25  global.window = {};
26  // @ts-ignore
27  global.navigator = { maxTouchPoints: 0 };
28  expect(isTouchDevice()).toBe(false);
29});
30
31test('returns false if window is undefined', () => {
32  // @ts-ignore
33  delete global.window;
34  expect(isTouchDevice()).toBe(false);
35});

Common Use Cases

  • UI Interaction Optimization

    Adjust interface elements (like hover effects, drag handles, or click targets) for touch-friendly behavior.

  • Conditional Event Binding

    Attach touchstart or pointerdown events only when touch input is supported.

  • Feature Flags in Progressive Web Apps (PWA)

    Customize gesture support or control schemes based on touch capability.

  • Responsive UX Decisions

    Dynamically modify layout or input prompts (e.g., showing virtual joystick controls) based on input method.

Codebase: Utilities -> Platforms -> isTouchDevice | Yevhen Klymentiev