Note that there are some explanatory texts on larger screens.

plurals
  1. POListening to mousedown AND touchstart on devices that use touch and a mouse (e.g. Surface)
    primarykey
    data
    text
    <p>So, I've run across an interesting problem while working on a Web application for the Microsoft Surface.</p> <p>I want to add event listeners for when a user interacts with a DOM element. Now I can do:</p> <pre><code>if ('ontouchstart' in document.documentElement) { //Attach code for touch event listeners document.addEventListener("touchstart" myFunc, false); } else { //Attach code for mouse event listeners document.addEventListener("mousedown" myFunc, false); } </code></pre> <p>If the device didn't have a mouse input, this problem would be simple and the above code would work just fine. But the Surface (and many new Windows 8 computers) have BOTH a touch and mouse input. So the above code would only work when the user touched the device. The mouse event listeners would never be attached.</p> <p>So then I thought, well, I could do this:</p> <pre><code>if ('ontouchstart' in document.documentElement) { //Attach code for touch event listeners document.addEventListener("touchstart" myFunc, false); } //Always attach code for mouse event listeners document.addEventListener("mousedown" myFunc, false); </code></pre> <p>Devices that don't support touch wouldn't have the events attached, but a device that uses touch will register its handlers. The problem with this though is that <code>myFunc()</code> will be called twice on a touch device:</p> <ol> <li><code>myFunc()</code> will fire when "touchstart" is raised</li> <li>Because touch browsers typically go through the cycle <em>touchstart</em> -> <em>touchmove</em> -> <em>touchend</em> -> <em>mousedown</em> -> <em>mousemove</em> -> <em>mouseup</em> -> <em>click</em>, <code>myFunc()</code> will be called again in "mousedown"</li> </ol> <p>I've considered adding code to<code>myFunc()</code> such that it calls <code>e.preventDefault()</code> but this seems to also block <em>touchend</em> as well as <em>mousedown</em> / <em>mousemove</em> / <em>mouseup</em> on some browsers (<a href="http://code.google.com/p/android/issues/detail?id=19827">link</a>).</p> <p>I hate doing useragent sniffers, but it seems as if touch browsers have variations in how touch events are implemented.</p> <p>I must be missing something because it seems that surely these JavaScript implementations were decided with possibility of a browser supporting both a mouse and touch!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload