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

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

   2 Comments   
http://bit.ly/1BpqNWW

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.

Photo by Chung Chu

2 responses to “Detecting if a User is on a Touch Screen Device in JS

  1. Thanks, Edd. I was browsing for a way to eliminate modernizr as a dependency in my SVG image annotator library, since I only needed to see if my code was running on a touch device,

Leave a Reply

Your email address will not be published. Required fields are marked *