How to determine if the client is a touch device

48,672

Solution 1

You can use the following JS function:

function isTouchDevice() {
   var el = document.createElement('div');
   el.setAttribute('ongesturestart', 'return;'); // or try "ontouchstart"
   return typeof el.ongesturestart === "function";
}

Source: Detecting touch-based browsing.

Please note the above code only tests if the browser has support for touch, not the device.

Related links:

There may be detection in jquery for mobile and jtouch

Solution 2

if ("ontouchstart" in document.documentElement)
{
  alert("It's a touch screen device.");
}
else
{
 alert("Others devices");
}

most simple code i found after browsing a lot here and there

Solution 3

Include modernizer, which is a tiny feature detection library. Then you can use something like below.

if (Modernizr.touch){
   // bind to touchstart, touchmove, etc and watch `event.streamId`
} else {
   // bind to normal click, mousemove, etc
}

Solution 4

Using document.createEvent("TouchEvent") will not work on desktop-devices. So you can use it inside an if statement.

Note that this method could produce errors on non-touch devices. I would prefer checking for ontouchstart in document.documentElement.

Solution 5

Check out this post, it gives a really nice code snippet for what to do when touch devices are detected or what to do if touchstart event is called:

$(function(){
  if(window.Touch) {
    touch_detect.auto_detected();
  } else {
    document.ontouchstart = touch_detect.surface;
  }
}); // End loaded jQuery
var touch_detect = {
  auto_detected: function(event){
    /* add everything you want to do onLoad here (eg. activating hover controls) */
    alert('this was auto detected');
    activateTouchArea();
  },
  surface: function(event){
    /* add everything you want to do ontouchstart here (eg. drag & drop) - you can fire this in both places */
    alert('this was detected by touching');
    activateTouchArea();
  }
}; // touch_detect
function activateTouchArea(){
  /* make sure our screen doesn't scroll when we move the "touchable area" */
  var element = document.getElementById('element_id');
  element.addEventListener("touchstart", touchStart, false);
}
function touchStart(event) {
  /* modularize preventing the default behavior so we can use it again */
  event.preventDefault();
}
Share:
48,672
matt
Author by

matt

Updated on July 18, 2020

Comments

  • matt
    matt almost 4 years

    is there any nice and clean method or trick to find out if the user is on a touch-device or not?

    I know there is stuff like var isiPad = navigator.userAgent.match(/iPad/i) != null;

    but I simply wonder if there is a trick to generally determine if the user is on Touch device? Because there are a lot more touch devices and tablets out there then just iPads.

    thank you.