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

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

I’ve written a jQuery plug-in that’s for use on both desktop and mobile devices. I wondered if there is a way with JavaScript to detect if the device has touch screen capability. I’m using jquery-mobile.js to detect the touch screen events and it works on iOS, Android etc., but I’d also like to write conditional statements based on whether the user’s device has a touch screen.
Is that possible?

Solutions/Answers:

Solution 1:

Update: Please read blmstr’s answer below before pulling a whole feature detection library into your project. Detecting actual touch support is more complex, and Modernizr only covers a basic use case.

Modernizr is a great, lightweight way to do all kinds of feature detection on any site.

It simply adds classes to the html element for each feature.

You can then target those features easily in CSS and JS. For example:

html.touch div {
    width: 480px;
}

html.no-touch div {
    width: auto;
}

And Javascript (jQuery example):

$('html.touch #popup').hide();

Solution 2:

Have you tried using this function? (This is the same as Modernizr used to use.)

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

UPDATE 1

document.createEvent("TouchEvent") have started to return true in the latest chrome (v. 17). Modernizr updated this a while ago. Check Modernizr test out here.

Update your function like this to make it work:

function is_touch_device() {
  return 'ontouchstart' in window;
}

UPDATE 2

I found that the above wasn’t working on IE10 (returning false on MS Surface). Here is the fix:

function is_touch_device() {
  return 'ontouchstart' in window        // works on most browsers 
      || 'onmsgesturechange' in window;  // works on IE10 with some false positives
};

UPDATE 3

'onmsgesturechange' in window will return true in some IE desktop versions so thats not reliable. This works slightly more reliably:

function is_touch_device() {
  return 'ontouchstart' in window        // works on most browsers 
      || navigator.maxTouchPoints;       // works on IE10/11 and Surface
};

UPDATE 2018

Time goes by and there are new and better ways to test this. I’ve basically extracted and simplified Modernizr’s way of checking it:

function is_touch_device() {
  var prefixes = ' -webkit- -moz- -o- -ms- '.split(' ');
  var mq = function(query) {
    return window.matchMedia(query).matches;
  }

  if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
    return true;
  }

  // include the 'heartz' as a way to have a non matching MQ to help terminate the join
  // https://git.io/vznFH
  var query = ['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join('');
  return mq(query);
}

Here they are using the non-standard touch-enabled media query feature, which I think is kinda weird and bad practice. But hey, in the real world I guess it works. In the future (when they are supported by all) those media query features could give you the same results: pointer and hover.

Check out the source of how Modernizr are doing it.

For a good article that explains the issues with touch detection, see:
Stu Cox: You Can’t Detect a Touchscreen.

Solution 3:

As Modernizr doesn’t detect IE10 on Windows Phone 8/WinRT, a simple, cross-browser solution is:

var supportsTouch = 'ontouchstart' in window || navigator.msMaxTouchPoints;

You only ever need to check once as the device won’t suddenly support or not support touch, so just store it in a variable so you can use it multiple times more efficiently.

Solution 4:

Using all the comments above I’ve assembled the following code that is working for my needs:

var isTouch = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0));

I have tested this on iPad, Android (Browser and Chrome), Blackberry Playbook, iPhone 4s, Windows Phone 8, IE 10, IE 8, IE 10 (Windows 8 with Touchscreen), Opera, Chrome and Firefox.

It currently fails on Windows Phone 7 and I haven’t been able to find a solution for that browser yet.

Hope someone finds this useful.

Solution 5:

I like this one:

function isTouchDevice(){
    return typeof window.ontouchstart !== 'undefined';
}

alert(isTouchDevice());

Solution 6:

If you use Modernizr, it is very easy to use Modernizr.touch as mentioned earlier.

However, I prefer using a combination of Modernizr.touch and user agent testing, just to be safe.

var deviceAgent = navigator.userAgent.toLowerCase();

var isTouchDevice = Modernizr.touch || 
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/)  || 
deviceAgent.match(/(iemobile)/) || 
deviceAgent.match(/iphone/i) || 
deviceAgent.match(/ipad/i) || 
deviceAgent.match(/ipod/i) || 
deviceAgent.match(/blackberry/i) || 
deviceAgent.match(/bada/i));

if (isTouchDevice) {
        //Do something touchy
    } else {
        //Can't touch this
    }

If you don’t use Modernizr, you can simply replace the Modernizr.touch function above with ('ontouchstart' in document.documentElement)

Also note that testing the user agent iemobile will give you broader range of detected Microsoft mobile devices than Windows Phone.

Also see this SO question