title: Detecting Touch Devices With Jquery
body: <p>I've spent a fair bit of time on the web looking at the various ways of detecting a touch device, but this surprisingly complicated issue does not seem to have a definitive answer. Based on <a href="http://www.stucox.com/blog/you-cant-detect-a-touchscreen/" rel="nofollow">this article</a>, I've decided to pursue the following approach.</p>
  
  <pre><code>// Run immediately and assign a global variable (touch_enabled) so it is accessible anywhere.
  
  // First try to detect (not entirely reliable)
  window.touch_enabled = !!('ontouchstart' in window) || !!('onmsgesturechange' in window);
  
  // Overwrite/set touch enabled to false on mousemove
  $(window).on('mousemove', function() { window.touch_enabled = false; });
  
  // Overwrite/set touch enabled to true on touchstart
  $(window).on('touchstart', function () { window.touch_enabled = true; });
  </code></pre>
  
  <p>I'm wondering if anyone can point out any issues with this method. I have not field tested it yet and will be doing so right away, but any second opinions would be appreciated.</p>
  
  <p>Below is a quick demo.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>window.touch_enabled = !!('ontouchstart' in window) || !!('onmsgesturechange' in window);
  $(window).on('mousemove', function() { window.touch_enabled = false; });
  $(window).on('touchstart', function () { window.touch_enabled = true; });
  
  setInterval(function() { $('.output').text(window.touch_enabled); }, 200);</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt;
  
  Touch Enabled = &lt;span class="output"&gt;&lt;/span&gt;</code></pre>
  </div>
  </div>
  </p>