Explain Codes LogoExplain Codes Logo

What's the best way to detect a 'touch screen' device using JavaScript?

javascript
touch-events
pointer-events
modernizr
Anton ShumikhinbyAnton Shumikhin·Aug 29, 2024
TLDR

Let's quickly cut to the chase:

const isTouchDevice = !!('ontouchstart' in window || navigator.maxTouchPoints);

This little piece of code checks for the ontouchstart event or any touch points available, revealing if the device is touch-compatible.

Weaving through the browser maze

In the diverse ecosystem of browsers, each has its unique approach to touch characteristics. These differences are crucial when detecting touch capabilities.

The Internet Explorer boomerang

Remember the good ol' Internet Explorer? It uses msMaxTouchPoints instead of maxTouchPoints. Here's how to handle it:

const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0; // Internet Explorer refuses to retire, doesn't it? 😉

The 'pointer: coarse' correlation

Modern browsers offer an elegant, unified way of dealing with pointer inputs – Mouse and Touch events, through the Pointer Events API. So let's capitalize on it:

const isTouchCapable = matchMedia('(pointer: coarse)').matches; // 'pointer: coarse' - Even pointers have tough days, don't they? 😄

The Modernizr magic

For advanced touch feature detection, Modernizr proves to be a great tool - an Aladdin's lamp for your JavaScript needs:

// Assuming Modernizr is loaded on your page if (Modernizr.touch) { // Tango with touch events here } // Who needs a genie when you've got Modernizr? 😜

Why do we need detection?

Detecting touch capabilities extends beyond the how-to. It's also crucially about the 'why' behind it.

User Experience: Adapting for touch

Craft an enriching UX by enhancing interactive elements like buttons, navigation menus, sliders for more relaxed touch interactions.

Store and Retrieve: Quick and Efficient

Store the touch detection result, avoiding repeated checks. Could be a wise step towards boosting your app's performance!

Test Across Devices: Leave none unchecked

Your app must shine on all devices, ensure you test your touch detection across a variety of devices for reliability and cross-browser compatibility.

The path forward

The world of devices evolves relentlessly. Your touch detection strategy should too!

Embrace the any-pointer realm

In a world teeming with diverse input types, adapting to any kind of pointer could be a game-changer:

const isPotentialTouch = matchMedia('(any-pointer: coarse)').matches; // 'any-pointer: coarse' – When pointers unite for a common cause

Modern Feature detection: Behind the scenes

Why? Over How? Wisdom from the likes of Stu Cox and Patrick H. Lauke could be your guiding light in this quest.

Be a ‘library minimalist’

Guiding principle: only integrate third-party libraries if they serve a unique need beyond the capabilities of vanilla JavaScript!