title: JavaScript touchend versus click dilemma
body: <p>I am working on some javascript UI, and using a lot of touch events like 'touchend' for improved response on touch devices. However, there are some logical issues which are bugging me ...</p>
  
  <p>I have seen that many developers mingle 'touchend' and 'click' in the same event. In many cases it will not hurt, but essentially the function would fire twice on touch devices:</p>
  
  <pre><code>button.on('click touchend', function(event) {
    // this fires twice on touch devices
  });
  </code></pre>
  
  <p>It has been suggested that one could detect touch capability, and set the event appropriately for example:</p>
  
  <pre><code>var myEvent = ('ontouchstart' in document.documentElement) ? 'touchend' : 'click';
  button.on(myEvent, function(event) {
    // this fires only once regardless of device
  });
  </code></pre>
  
  <p>The problem with the above, is that it will break on devices that support both touch and mouse. If the user is currently using mouse on a dual-input device, the 'click' will not fire because only 'touchend' is assigned to the button.</p>
  
  <p>Another solution is to detect the device (e.g. "iOS") and assign an event based on that:
  <a href="https://stackoverflow.com/questions/8503453/click-event-called-twice-on-touchend-in-ipad">Click event called twice on touchend in iPad</a>.
  Of course, the solution in the link above is only for iOS (not Android or other devices), and seems more like a "hack" to solve something quite elementary.</p>
  
  <p>Another solution would be to detect mouse-motion, and combine it with touch-capability to figure out if the user is on mouse or touch. Problem of course being that the user might not be moving the mouse from when you want to detect it ...</p>
  
  <p>The most reliable solution I can think of, is to use a simple <a href="http://benalman.com/projects/jquery-throttle-debounce-plugin/" rel="noreferrer">debounce</a> function to simply make sure the function only triggers once within a short interval (for example 100ms):</p>
  
  <pre><code>button.on('click touchend', $.debounce(100, function(event) {
    // this fires only once on all devices
  }));
  </code></pre>
  
  <p>Am I missing something, or does anyone have any better suggestions?</p>
  
  <p><em>Edit:</em> I found this link after my post, which suggests a similar solution as the above:
  <a href="https://stackoverflow.com/questions/7018919/how-to-bind-touchstart-and-click-events-but-not-respond-to-both">How to bind &#39;touchstart&#39; and &#39;click&#39; events but not respond to both?</a></p>