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

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.

Photo by Chung Chu

10 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,

  2. Sorry, but this doesn’t work. Just typed ” ‘ontouchstart’ in document.documentElement” in my desktop Chrome console and got “true”.

    1. Maybe we should check if the “ontouchstart” actually has a value, not if it exists in the object? Something like:

      return !!(document.documentElement.ontouchstart) // convert to boolean

  3. Nope – according to BrowserStack, document.documentElement.ontouchstart returns null for a Samsung tablet device. Back to user agent strings, I guess.

    1. Ahh I’m sorry to hear this Gilad – back to the drawing board, I’ll try to update this post once I know a bit more…

  4. I have a lenovo yoga laptop with a touch display. It certainly supports ontouchstart but in a weird way. Do you have an idea how to tell it’s not a mobile?

  5. I try on surface pro and it works. Wish it works on other desktops with touchscreens.
    var is_touch_device = ‘ontouchstart’ in window ||
    navigator.maxTouchPoints > 0 ||
    window.navigator.msMaxTouchPoints > 0;

Leave a Reply

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