How to detect a touch device using JavaScript

Detecting a TouchEvent

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

User agent

if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent))
{ 
  // some code.. 
}