How to detect a touch device using JavaScript

A while back I had to make a navigation menu which played a sound when you moused over the various menu points.

The problem was, that this feature didn’t play nicely with touch devices, as they don’t really have a concept of hover.

What happened instead was that the sound would play when the user selected one of the menu points, but would get cut off as the new page loaded – eurgh!

So, I started looking for a way to detect a touch device and to disable this functionality accordingly.

I tried quite a few little hacks, from user agent sniffing:

if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent))
{ 
  // some code.. 
}

to creating and detecting a TouchEvent:

function is_touch_device() {
  try {
    document.createEvent("TouchEvent");
    return true;
  } catch (e) {
    return false;
  }
}

While these kind of worked, they either felt kind of hacky or returned too many false positives.

I eventually settled on a nifty solution using  modenizr, a tiny feature detection library.

With this included in my page, I could then write:

if (Modernizr.touch){
   // disable sound
} else {
   // attach sound to menu
}

I tested this on the iPad1, iPad2, iPhone3, iPhone4 and the latest version of Android and it worked just as expected.

Resources:

This post currently has 3 responses

  1. Matt Howlett says:

    Hey. Came across your article when searching for touch-option for a hover class CSS effect seen here:

    NMCEvent.ca/students

    Where did you find documentation about how to use modernizr’s touch detection? I’d like to change the hover to single-tap whenever the user is on mobile/touch device. Could you point me in the right direction?

    Thanks,

    • hibbard.eu says:

      Hi there,

      Thanks for your comments.

      The link you posted leads to a 404, I`m afraid, so I can’t see what you’re talking about.

      The little modenizr documentation that there is on touch detection, can be found here: http://modernizr.com/docs/#touch

      Apart from that, I found StackOverflow to be very helpful (see links above).

  2. AppMaisters says:

    A useful blog post on the topic, linked to from within the Modernizr source for detecting touch events. Conclusion: it’s not likely to reliably detect touchscreen devices from Javascript.

    http://www.stucox.com/blog/you-cant-detect-a-touchscreen/

Comments are closed!

I'm on Twitter:

Categories