Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript, detect touch devices

I'm using this function to detect if the device is a touch device:

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

Got this function from here: What's the best way to detect a 'touch screen' device using JavaScript?

But since Chrome 25 (25.0.1364) it returns true on my desktop which isn't a touch device. Also I've updated IE9 to IE10 and it returns true in IE!

Searched around but couldn't find anything useful to fix this except using a something like this: http://detectmobilebrowsers.com/

What do you recommend?

I'm looking forward to your responses!

like image 292
Roy Avatar asked Dec 12 '22 17:12

Roy


1 Answers

The code works just fine, the browser is able to understand touch events, just because your screen isn't touchable doesn't mean that the browser doesn't support the functionality. What you are looking to test is a hardware capability which isn't really testable. You can always use different ways though of seeing if the user is actual using a touch interface after touching it once, such as this article describes, or many others that larger libraries use such as Modernizer.

As a reference the code actually used in the article above is:

function isTouchDevice() {
   var el = document.createElement('div');
   el.setAttribute('ongesturestart', 'return;');
   if(typeof el.ongesturestart == "function"){
      return true;
   }else {
      return false
   }
}
like image 53
ars265 Avatar answered Jan 02 '23 01:01

ars265