Friday, February 7, 2014

Detecting Browser's Touch Capability Using Javascript


Since the beginning of 2014, Google Chrome returns TRUE on document.createEvent("TouchEvent") javascript call even the browser doesn't support any touch action. The following shows the function I've been using to sniff the touch capability and it is no longer working on the latest Google Chrome:

<script>

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

</script>


The following is the modified version to solve the latest Chrome browser on the touch sniffing function:

<script>

function is_touch_device() {

 var touch = 'ontouchstart' in window;
 return touch?true:false;

}

</script>


The sudden change in support for Chrome is a bit of a surprise to me though.

No comments:

Post a Comment