Detect touchscreen devices with JavaScript

There are a lot of ways to detect touchscreen devices with JavaScript. Here are my favorites:

function isTouchDevice(){
  return (typeof(window.ontouchstart) != 'undefined') ? true : false;
}
function isTouchDevice(){
  return ('ontouchstart' in window) ? true : false;
}
function isTouchDevice(){
  return 'ontouchstart' in window;
}

Execution:

if(isTouchDevice())
  alert('Touch me!');
else
  alert('Click me!');

Please note: Windows Phone 7 does not support touch events that’s why you should do this:

function isTouchDevice(){
  if(navigator.userAgent.match('Windows Phone')){
    return true;
  }else{
    return 'ontouchstart' in window;
  }
}

What I also like is the following approach:

if (window.navigator.msPointerEnabled) {
  alert('IE10 / Windows 8 / Touch, pen and mouse');
}
else if('ontouchstart' in window){
  alert('touch device');
}
else{
  alert('mouse device');
}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.