Detecting if a User is on a Touch Screen Device in JS

Whilst recently working with native date pickers on mobile browsers, Chrome and Opera we came across an issue. The native datepicker wasn’t acting as we wanted – but we had no control over it (you can’t trigger a native datepicker to open in Chrome!). Because of this we wanted to fallback to a custom date picker (think jQuery UI) if a native date picker didn’t exist or if the browser is on a desktop.

We’ll focus on the ‘is on a desktop‘ bit here and work with datepickers more closely in another post.

The easiest way to detect if a user is on a desktop is to in fact switch it around and check if the user is not on a mobile. Using JavaScript we can test to see if the touch methods are present within document model. This is a much safer option than browser sniffing. Here’s the function we have to do this:

function isTouchDevice() {
    return 'ontouchstart' in document.documentElement;

With this function we can then use it where ever we like:

if (isTouchDevice()) {
    // on Mobile
else {
    // on Desktop

If you’re after more information on this there a few good blog posts on it.