Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Getting touchy - Everything you (n)ever wanted to know about touch and pointer events / JavaScript Days 2017

Getting touchy - Everything you (n)ever wanted to know about touch and pointer events / JavaScript Days 2017

Beyond smartphones and tablets, touchscreens are finding their way into laptops and even desktop computers. With hardware support for touch becoming increasingly ubiquitous, it's time to explore what new possibilities are available to developers. This session will cover the basics of handling touch events - from making sure simple single-tap interactions are as responsive as possible, all the way to examples of full multitouch, gesture-enabled elements.

Evergreen slidedeck at https://patrickhlauke.github.io/getting-touchy-presentation/ / https://github.com/patrickhlauke/getting-touchy-presentation

Patrick H. Lauke

March 22, 2017
Tweet

More Decks by Patrick H. Lauke

Other Decks in Technology

Transcript

  1. getting touchy EVERYTHING YOU (N)EVER WANTED TO KNOW ABOUT TOUCH

    AND POINTER EVENTS Patrick H. Lauke / JavaScript Days 2017 / 22 March 2017 / Munich
  2. about me... •  senior accessibility consultant at The Paciello Group

    •  previously developer relations at Opera •  co-editor Touch Events Level 2 •  WG chair and co-editor Pointer Events Level 2
  3. compatibility mouse events (mouseenter) > mouseover > mousemove* > mousedown

    > (focus) > mouseup > click * only a single “sacrificial” mousemove event fired
  4. on first tap (mouseenter) > mouseover > mousemove > mousedown

    > (focus) > mouseup > click subsequent taps mousemove > mousedown > mouseup > click tapping away (mouseout) > (blur) focus / blur only on focusable elements; subtle differences between browsers Mobile/tablet touchscreen activation/tap event order
  5. touch events introduced by Apple, adopted in Chrome/Firefox/Opera (and belatedly

    IE/Edge – more on that later) www.w3.org/TR/touch-events
  6. events fired on tap touchstart > [touchmove]+ > touchend >

    (mouseenter) > mouseover > mousemove > mousedown > (focus) > mouseup > click (mouse events only fired for single-finger tap)
  7. on first tap touchstart > [touchmove]+ > touchend > (mouseenter)

    > mouseover > mousemove > mousedown > (focus) > mouseup > click subsequent taps touchstart > [touchmove]+ > touchend > mousemove > mousedown > mouseup > click tapping away mouseout > (mouseleave) > (blur)
  8. •  too many touchmove events prevent mouse compatibility events after

    touchend (not considered a "clean" tap) •  too many touchmove events on activatable elements can lead to touchcancel (in old Chrome/Browser versions) •  not all browsers consistently send touchmove •  differences in focus / blur and some mouse compatibility events (e.g. mouseenter / mouseleave ) •  some events may only fire when tapping away to another focusable element (e.g. blur ) some browsers outright weird...
  9. Browser/Android 4.3 mouseover > mousemove > touchstart > touchend >

    mousedown > mouseup > click Browser/Blackberry PlayBook 2.0 touchstart > mouseover > mousemove > mousedown > touchend > mouseup > click UC Browser 10.8/Android 6 mouseover > mousemove > touchstart > (touchmove)+ > touchend > mousedown > focus > mouseup > click
  10. /* feature detection for touch events */ if ( 'ontouchstart'

    in window ) { /* some clever stuff here */ } /* older browsers have flaky support so more hacky tests needed...use Modernizr.touch or similar */
  11. /* conditional "touch OR mouse/keyboard" event binding */ if ('ontouchstart'

    in window) { // set up event listeners for touch ... } else { // set up event listeners for mouse/keyboard ... }
  12. Android + mouse – like touch (mouse emulating touch) touchstart

    > touchend > mouseover > mousemove > mousedown > (focus) > mouseup > click
  13. Android + Chrome 58 + mouse – like desktop mouse

    events (+ pointer events) + click
  14. Blackberry PlayBook 2.0 + mouse – like desktop mouseover >

    mousedown > (mousemove)+ > mouseup > click
  15. Blackberry Leap (BBOS 10.1) + mouse – like desktop mouseover

    > mousedown > (mousemove)+ > mouseup > click
  16. iOS + keyboard – similar to touch (using VO +

    SPACE ) focus / touchstart > touchend > (mouseenter) > mouseover > mousemove > mousedown > blur > mouseup > click
  17. iOS + VoiceOver (with/without keyboard) – similar to touch focus

    / touchstart > touchend > (mouseenter) > mouseover > mousemove > mousedown > blur > mouseup > click
  18. Android 6.1/Chrome + TalkBack – like touch touchstart > touchend

    > mouseover > mouseenter > mousemove > mousedown > focus > mouseup > click
  19. Android 6.1/Firefox + TalkBack – similar to touch touchstart >

    mousedown > focus > touchend > mouseup > click
  20. further scenarios? •  desktop with external touchscreen •  touchscreen laptop

    with non-touch second screen •  touchscreen laptop with trackpad/mouse •  ...and other permutations?
  21. note on trackpad gestures •  trackpads that allow multi-finger gestures

    (e.g. recent MacBooks, Magic Mouse/Trackpad, Windows precision trackpad, ASUS Smart Gesture, Wacom Intuos Pro gestures etc) don't fire touch events / expose touch points •  these gestures are handled directly by the OS/driver and don't reach the browser as raw touches •  Wacom Intuos Pro touch input exposed as mouse to OS •  OS X/Safari 9.1+ does fire Apple's proprietary gesture* events (for pinch-to-zoom, rotation)
  22. /* feature detection for touch events */ if ('ontouchstart' in

    window) { /* browser supports touch events but user is not necessarily using touch (exclusively) */ /* it could be a mobile, tablet, desktop, fridge ... */ }
  23. Interaction Media Features pointer / hover relate to “primary” pointing

    device any-pointer / any-hover relate to all pointing devices /* the primary input is ... */ @media (pointer: fine) { /* a mouse, stylus, ... */ } @media (pointer: coarse) { /* a touchscreen, ... */ } @media (pointer: none) { /* not a pointer (e.g. d-pad) */ } @media (hover: hover) { /* hover-capable */ } @media (hover: none) { /* not hover-capable */ } hover: on-demand / any-hover: on-demand removed in recent drafts
  24. Interaction Media Features pointer / hover relate to “primary” pointing

    device any-pointer / any-hover relate to all pointing devices /* across all detected pointing devices at least one is ... */ @media (any-pointer: fine) { /* a mouse, stylus, ... */ } @media (any-pointer: coarse) { /* a touchscreen, ... */ } @media (any-pointer: none) { /* none of them are pointers */ } @media (any-hover: hover) { /* hover-capable */ } @media (any-hover: none) { /* none of them are hover-capable */ } hover: on-demand / any-hover: on-demand removed in recent drafts
  25. Media Features and JavaScript if (window.matchMedia("(any-pointer:coarse)").matches) { ... } /*

    listen for dynamic changes */ window.matchMedia("(any-pointer:coarse)")↵ .onchange = function(e) { ... } window.matchMedia("(any-pointer:coarse)")↵ .addEventListener("change", function(e) { ... } , false } window.matchMedia("(any-pointer:coarse)")↵ .removeEventListener("change", function(e) { ... } , false }
  26. /* Naive uses of Interaction Media Features */ @media (pointer:

    fine) { /* primary input has fine pointer precision... so make all buttons/controls small? */ } @media (hover: hover) { /* primary input has hover...so we can rely on it? */ } /* pointer and hover only check "primary" input, but what if there's a secondary input that lacks capabilities? */
  27. /* Better uses of Interaction Media Features */ @media (any-pointer:

    coarse) { /* at least one input has coarse pointer precision... provide larger buttons/controls for touch */ } /* test for *any* "least capable" inputs (primary or not) */ Limitation: [mediaqueries-4] any-hover can't be used to detect mixed hover and non-hover capable pointers. Also, pointer / hover / any-pointer / any-hover don't cover non-pointer inputs (e.g. keyboards) – always assume non-hover-capable inputs @media (any-hover: none) { /* at least one input lacks hover capability... don't rely on it or avoid altogether */ }
  28. if in doubt, offer a way to switch interfaces... or

    just always use a touch-optimised interface
  29. touch / mouse events delay touchstart > [touchmove]+ > touchend

    > [300ms delay] (mouseenter) > mouseover > mousemove > mousedown > (focus) > mouseup > click
  30. touchend for a control that fires after finger lifted (but

    this can result in events firing after zoom/scroll)
  31. /* DON'T DO THIS: conditional "touch OR mouse/keyboard" event binding

    */ if ('ontouchstart' in window) { // set up event listeners for touch foo.addEventListener('touchend', ...); ... } else { // set up event listeners for mouse/keyboard foo.addEventListener('click', ...); ... }
  32. /* DO THIS: doubled-up "touch AND mouse/keyboard" event binding */

    // set up event listeners for touch foo.addEventListener('touchend', ...); // set up event listeners for mouse/keyboard foo.addEventListener('click', ...); /* but this would fire our function twice for touch? */ patrickhlauke.github.io/touch/tests/event-listener_naive-event-doubling.html
  33. /* DO THIS: doubled-up "touch AND mouse/keyboard" event binding */

    // set up event listeners for touch foo.addEventListener('touchend', function(e) { // prevent compatibility mouse events and click e.preventDefault(); ... }); // set up event listeners for mouse/keyboard foo.addEventListener('click', ...); patrickhlauke.github.io/touch/tests/event-listener_naive-event-doubling-fixed.html
  34. Bug 151077 - Fast-clicking should trigger when scale is equal

    to explicitly set initial scale (from iOS 9.3 onwards)
  35. suppressing 300ms delay if your code does rely on handling

    click / mouse events: •  "mobile optimised" <meta name="viewport" content="width=device-width"> •  add touch-action:manipulation in CSS (part of Pointer Events) •  use helper library like fastclick.js for older browsers •  make your viewport non-scalable...
  36. events fired on tap touchstart > [touchmove]+ > touchend >

    (mouseenter) > mouseover > mousemove* > mousedown > (focus) > mouseup > click * mouse event emulation fires only a single mousemove too many touchmove events prevent mouse compatibility events after touchend
  37. var posX, posY; function positionHandler(e) { posX = e.clientX ;

    posY = e.clientY ; } canvas.addEventListener(' mousemove ', positionHandler, false);
  38. var posX, posY; function positionHandler(e) { posX = e.clientX ;

    posY = e.clientY ; } canvas.addEventListener(' mousemove ', positionHandler, false); canvas.addEventListener(' touchmove ', positionHandler, false); /* but this won't work for touch... */
  39. interface MouseEvent : UIEvent { readonly attribute long screenX ;

    readonly attribute long screenY ; readonly attribute long clientX ; readonly attribute long clientY ; readonly attribute boolean ctrlKey; readonly attribute boolean shiftKey; readonly attribute boolean altKey; readonly attribute boolean metaKey; readonly attribute unsigned short button; readonly attribute EventTarget relatedTarget; // [DOM4] UI Events readonly attribute unsigned short buttons; }; www.w3.org/TR/DOM-Level-2-Events/events.html#Events-MouseEvent www.w3.org/TR/uievents/#events-mouseevents
  40. partial interface MouseEvent { readonly attribute double screenX; readonly attribute

    double screenY; readonly attribute double pageX ; readonly attribute double pageY ; readonly attribute double clientX; readonly attribute double clientY; readonly attribute double x ; readonly attribute double y ; readonly attribute double offsetX ; readonly attribute double offsetY ; }; www.w3.org/TR/cssom-view/#extensions-to-the-mouseevent- interface
  41. interface TouchEvent : UIEvent { readonly attribute TouchList touches ;

    readonly attribute TouchList targetTouches ; readonly attribute TouchList changedTouches ; readonly attribute boolean altKey; readonly attribute boolean metaKey; readonly attribute boolean ctrlKey; readonly attribute boolean shiftKey; }; www.w3.org/TR/touch-events/#touchevent-interface
  42. interface Touch { readonly attribute long identifier; readonly attribute EventTarget

    target; readonly attribute long screenX ; readonly attribute long screenY ; readonly attribute long clientX ; readonly attribute long clientY ; readonly attribute long pageX ; readonly attribute long pageY ; }; www.w3.org/TR/touch-events/#touch-interface
  43. TouchList differences touches all touch points on screen targetTouches all

    touch points that started on the element changedTouches touch points that caused the event to fire
  44. changedTouches depending on event: •  for touchstart , all new

    touch points that became active •  for touchmove , all touch points that changed/moved since last event •  for touchend / touchcancel , touch points that were removed (and are not active anymore at this point)
  45. var posX, posY; function positionHandler(e) { if ((e.clientX)&&(e.clientY)) { posX

    = e.clientX; posY = e.clientY; } else if (e.targetTouches) { posX = e.targetTouches[0].clientX; posY = e.targetTouches[0].clientY; e.preventDefault() ; } } canvas.addEventListener('mousemove', positionHandler, false ); canvas.addEventListener('touchmove', positionHandler, false );
  46. TouchList collections order •  order of individual Touch objects in

    a TouchList can change •  e.g. targetTouches[0] not guaranteed to always be the same finger when dealing with multitouch •  not problematic for single-finger interactions, but use identifier property for each Touch to explicitly track a particular touch point / finger in multitouch
  47. implicit capture •  touch events have implicit capture: once you

    start a touch movement on an element, events keep firing to the element even when moving outside the element's boundaries •  compare to mouse events, which require tricks to track mouse
  48. /* Swipe detection from basic principles */ Δt = end.time

    - start.time; Δx = end.x - start.x; Δy = end.y - start.y; if (( Δt > timeThreshold ) || ( (Δx + Δy) < distanceThreshold )) { /* too slow or movement too small */ } else { /* it's a swipe! - use Δx and Δy to determine direction - pythagoras √( Δx² + Δy² ) for distance - distance/Δt to determine speed */ }
  49. Function.prototype.debounce = function (milliseconds, context) { var baseFunction = this,

    timer = null, wait = milliseconds; return function () { var self = context || this, args = arguments; function complete() { baseFunction.apply(self, args); timer = null; } if (timer) { clearTimeout(timer); } timer = setTimeout(complete, wait); }; }; window.addEventListener('touchmove', myFunction.debounce(250) );
  50. Function.prototype.throttle = function (milliseconds, context) { var baseFunction = this,

    lastEventTimestamp = null, limit = milliseconds; return function () { var self = context || this, args = arguments, now = Date.now(); if (!lastEventTimestamp || now - lastEventTimestamp >= limit) { lastEventTimestamp = now; baseFunction.apply(self, args); } }; }; window.addEventListener('touchmove', myFunction.throttle(250) );
  51. interface TouchEvent : UIEvent { readonly attribute TouchList touches ;

    readonly attribute TouchList targetTouches ; readonly attribute TouchList changedTouches ; readonly attribute boolean altKey; readonly attribute boolean metaKey; readonly attribute boolean ctrlKey; readonly attribute boolean shiftKey; }; www.w3.org/TR/touch-events/#touchevent-interface
  52. /* iterate over relevant TouchList */ for (i=0; i< e.targetTouches

    .length; i++) { ... posX = e.targetTouches[i].clientX ; posY = e.targetTouches[i].clientY ; ... }
  53. /* iOS/Safari/WebView has gesture events for size/rotation, not part of

    the W3C Touch Events spec */ /* gesturestart / gesturechange / gestureend */ foo.addEventListener('gesturechange', function(e) { /* e.scale e.rotation */ /* values can be plugged directly into CSS transforms etc */ }); /* not supported in other browsers, but potentially useful for iOS exclusive content (hybrid apps/webviews) */ iOS Developer Library - Safari Web Content Guide - Handling gesture events
  54. /* Pinch/rotation detection from basic principles */ Δx = x2

    - x1; Δy = y2 - y1; /* pythagoras √( Δx² + Δy² ) to calculate distance */ Δd = Math.sqrt( (Δx * Δx) + (Δy * Δy) ); /* trigonometry to calculate angle */ α = Math.atan2( Δy, Δx ); Mozilla Developer Network: Math.atan2()
  55. e.g. older versions of Chrome fire touchcancel on scroll/zoom YouTube:

    Google Developers - Mobile Web Thursdays: Performance on Mobile
  56. not defined in spec (yet), but de facto yes in

    most modern browsers patrickhlauke.github.io/touch/gesture-touch
  57. touchmove and scroll •  useful for common interactions like pull

    to refresh – let browser (over)scroll and track movement •  has scroll performance impact, as browser is blocked on event listener in case it cancels the scroll (see passive event listeners)
  58. Historically (until end of 2016?), Apple suggested adding dummy onclick=""

    handlers iOS Developer Library - Safari Web Content Guide - Handling Events
  59. dummy onclick="" handlers are unnecessary (at least since iOS6) Apple

    quietly dropped this from their documentation... patrickhlauke.github.io/touch/ios-clickable/
  60. mouse + click bubbling in iOS •  target element is

    a link or form control •  target or any ancestor (up to but not including body ) has explicit mouse or click handler (even if only empty function) •  target or any ancestor (up to and including document ) has cursor:pointer Quirksmode: Mouse event bubbling in iOS
  61. iOS quirks in a nutshell if your code does rely

    on handling mouse events: •  you don't need dummy click handlers to make arbitrary (non- interactive) elements react to mouse events (such as mouseover , mousedown , mouseup ...) •  you do need to do extra work if you rely on event bubbling / event delegation of mouse events (including click )
  62. /* Extension to touch objects */ partial interface Touch {

    readonly attribute float radiusX; readonly attribute float radiusY; readonly attribute float rotationAngle; readonly attribute float force; };
  63. /* Touch Events – contact geometry */ partial interface Touch

    { readonly attribute float radiusX ; readonly attribute float radiusY ; readonly attribute float rotationAngle ; readonly attribute float force; };
  64. /* Touch Events – force */ partial interface Touch {

    readonly attribute float radiusX; readonly attribute float radiusY; readonly attribute float rotationAngle; readonly attribute float force ; }; force : value in range 0 – 1 . if no hardware support 0 (some devices, e.g. Nexus 10, "fake" force based on radiusX / radiusY )
  65. 3D Touch ≠ Force Touch •  Force Touch is Apple's

    proprietary extension to mouse events •  only aimed at force-enabled trackpads (new Apple models) •  new events: webkitmouseforcewillbegin , webkitmouseforcedown , webkitmouseforceup , webkitmouseforcechanged •  mouse events have additional webkitForce property Safari Developer Library: Responding to Force Touch Events
  66. interface Touch { readonly attribute long identifier; readonly attribute EventTarget

    target; readonly attribute long float screenX; readonly attribute long float screenY; readonly attribute long float clientX; readonly attribute long float clientY; readonly attribute long float pageX; readonly attribute long float pageY; };
  67. W3C Web Events WG - Touch Events errata (early effort

    to clarify grey areas, simplify language used)
  68. W3C Touch Events Level 2 (Editor's Draft) (merges errata, touch

    events extensions, fractional touch coordinates)
  69. ...and some new inputs (though currently mapped to mouse) Building

    Xbox One Apps using HTML and JavaScript YouTube: Xbox One Edge Browser sends Pointer Events
  70. events fired on tap (Edge) mousemove* > pointerover > mouseover

    > pointerenter > mouseenter > pointerdown > mousedown > focus gotpointercapture > pointermove > mousemove > pointerup > mouseup > lostpointercapture > click > pointerout > mouseout > pointerleave > mouseleave mouse events fired “inline” with pointer events (for a primary pointer, e.g. first finger on screen)
  71. IE10/IE11 quirks •  vendor-prefixed in IE10 ( MSPointerDown ..., navigator.msMaxTouchPoints

    , -ms-touch-action ) •  unprefixed in IE11 (but prefixed versions mapped for compatibility) •  event order (when click is fired) incorrect in IE10/IE11 see W3C Pointer Events WG mailing list - Jacob Rossi (Microsoft)
  72. Chrome, Edge (on mobile), IE11 (Windows Phone 8.1update1) support both

    Touch Events and Pointer Events w3c.github.io/pointerevents/#mapping-for-devices-that-do-not-support-hover
  73. about:flags in Microsoft Edge to turn on touch events on

    desktop (e.g. touch-enabled laptops) – off by default for site compatibility
  74. ... when touch events also supported (Edge) pointerover > pointerenter

    > pointerdown > touchstart > pointerup > touchend > mouseover > mouseenter > mousemove > mousedown > focus > mouseup > click > pointerout > pointerleave Specific order of events is not defined in the spec in this case – will vary between browsers... only problem if handling both pointer events and mouse events (which is nonsensical)
  75. /* Pointer Events extend Mouse Events vs Touch Events and

    their new objects / TouchLists / Touches */ interface PointerEvent : MouseEvent { readonly attribute long pointerId; readonly attribute long width; readonly attribute long height; readonly attribute float pressure; readonly attribute float tangentialPressure; /* Level 2 */ readonly attribute long tiltX; readonly attribute long tiltY; readonly attribute long twist; /* Level 2 */ readonly attribute DOMString pointerType; readonly attribute boolean isPrimary; }
  76. handling mouse input is exactly the same as traditional mouse

    events (only change pointer* instead of mouse* event names)
  77. handling touch or stylus is also exactly the same as

    traditional mouse events (mouse code can be adapted to touch/stylus quickly)
  78. /* detecting pointer events support */ if ( window.PointerEvent )

    { /* some clever stuff here but this covers touch, stylus, mouse, etc */ } /* still listen to click for keyboard! */
  79. /* detect maximum number of touch points */ if (

    navigator.maxTouchPoints > 0 ) { /* device with a touchscreen */ } if ( navigator.maxTouchPoints > 1 ) { /* multitouch-capable device */ } "you can detect a touchscreen" ...but user may still use other input mechanisms
  80. pointer / mouse events and delay ... [300ms delay] click

    ... 300ms delay just before click event
  81. •  double-up pointerup and click listeners? •  prevent code firing

    twice with preventDefault ? won't work: preventDefault() stops mouse compatibility events, but click is not considered mouse compatibility event
  82. touch-action what action should the browser handle? touch-action: auto /*

    default */ touch-action: none touch-action: pan-x touch-action: pan-y touch-action: manipulation /* pan/zoom */ touch-action: pan-x pan-y /* can be combined */ www.w3.org/TR/pointerevents/#the-touch-action-css-property only determines default touch action, does not stop compatibility mouse events nor click
  83. Pointer Events Level 2 expanded set of values (useful for

    pull-to-refresh, carousels, etc) touch-action: pan-left touch-action: pan-right touch-action: pan-up touch-action: pan-down touch-action: pan-left pan-down /* can be combined */ touch-action: pan-x pan-down /* can be combined */ w3c.github.io/pointerevents/#the-touch-action-css-property new values only determine allowed pan direction at the start of the interaction; once panning starts, user can also move in opposite direction along same axis
  84. although it's called "touch-action", it applies to any pointer type

    that pans/zooms (e.g. Samsung Note + stylus, Chrome <58/Android + mouse) w3c.github.io/pointerevents/#declaring-candidate-regions-for-default-touch-behaviors
  85. Windows 10 build 15007 on Mobile ignores unscalable viewports no

    delay until user zooms for first time...
  86. /* touch events: separate handling */ foo.addEventListener('touchmove', ... , false);

    foo.addEventListener('mousemove', ... , false); /* pointer events: single listener for mouse, stylus, touch */ foo.addEventListener(' pointermove ', ... , false);
  87. /* Reminder: Touch Events need separate code for x /

    y coords */ function positionHandler(e) { if ((e.clientX)&&(e.clientY)) { posX = e.clientX; posY = e.clientY; } else if (e.targetTouches) { posX = e.targetTouches[0].clientX; posY = e.targetTouches[0].clientY; ... } } canvas.addEventListener('mousemove', positionHandler, false ); canvas.addEventListener('touchmove', positionHandler, false );
  88. /* Pointer Events extend Mouse Events */ foo.addEventListener(' pointermove ',

    function(e) { ... posX = e.clientX ; posY = e.clientY ; ... }, false); www.w3.org/TR/pointerevents/#pointerevent-interface
  89. foo.addEventListener('pointermove', function(e) { ... switch( e.pointerType ) { case '

    mouse ': ... break; case ' pen ': ... break; case ' touch ': ... break; default : /* future-proof */ } ... } , false);
  90. /* in IE11/Edge, pointerType returns a string in IE10, the

    return type is long */ MSPOINTER_TYPE_TOUCH: 0x00000002 MSPOINTER_TYPE_PEN: 0x00000003 MSPOINTER_TYPE_MOUSE: 0x00000004 MSDN: IE Dev Center - API reference - pointerType property
  91. /* PointerEvents don't have the handy TouchList objects, so we

    have to replicate something similar... */ var points = []; switch (e.type) { case ' pointerdown ': /* add to the array */ break; case ' pointermove ': /* update the relevant array entry's x and y */ break; case ' pointerup ': case ' pointercancel ': /* remove the relevant array entry */ break; }
  92. simultaneous use of inputs is hardware-dependent (e.g. Surface 3 "palm

    blocking" prevents concurrent touch/stylus/mouse, but not touch/external mouse/external stylus)
  93. /* like iOS/Safari, IE/Edge have higher-level gestures , but these

    are not part of the W3C Pointer Events spec */ foo.addEventListener("MSGestureStart", ... , false) foo.addEventListener("MSGestureEnd", ... , false) foo.addEventListener("MSGestureChange", ... , false) foo.addEventListener("MSInertiaStart", ... , false) foo.addEventListener("MSGestureTap", ... , false) foo.addEventListener("MSGestureHold", ... , false) /* not supported in other browsers, but potentially useful for IE/Edge exclusive content (e.g. UWP packaged/hosted/hybrid web app); for web, replicate these from basic principles again... */ MSDN IE10 Developer Guide: Gesture object and events
  94. /* Pointer Events - pressure */ interface PointerEvent : MouseEvent

    { readonly attribute long pointerId; readonly attribute long width; readonly attribute long height; readonly attribute float pressure ; readonly attribute float tangentialPressure; readonly attribute long tiltX; readonly attribute long tiltY; readonly attribute long twist; readonly attribute DOMString pointerType; readonly attribute boolean isPrimary; } pressure : value in range 0 – 1 . if no hardware support, 0.5 in active button state, 0 otherwise
  95. hovering stylus •  hardware-dependant •   pointermove fires •  

    pressure == 0 (non-active button state) •  track pointerdown / pointerup to be safe
  96. /* Pointer Events - contact geometry */ interface PointerEvent :

    MouseEvent { readonly attribute long pointerId; readonly attribute long width ; readonly attribute long height ; readonly attribute float pressure; readonly attribute float tangentialPressure; readonly attribute long tiltX; readonly attribute long tiltY; readonly attribute long twist; readonly attribute DOMString pointerType; readonly attribute boolean isPrimary; } if hardware can't detect contact geometry, either 0 or "best guess" (e.g. for mouse/stylus, return width / height of 1 )
  97. /* Pointer Events - tilt */ interface PointerEvent : MouseEvent

    { readonly attribute long pointerId; readonly attribute long width; readonly attribute long height; readonly attribute float pressure; readonly attribute float tangentialPressure; readonly attribute long tiltX ; readonly attribute long tiltY ; readonly attribute long twist; readonly attribute DOMString pointerType; readonly attribute boolean isPrimary; } tiltX / tiltY : value in degrees -90 – 90 . returns 0 if hardware does not support tilt
  98. pointermove fires if any property changes, not just x/y position

    ( width , height , tiltX , tiltY , pressure )
  99. •  touch events have implicit capture: once you start a

    touch movement on an element, events keep firing to the element even when moving outside the element's boundaries •  for mouse / stylus: pointer events like mouse events: only fire events to an element while pointer inside it (but allow explicit capture) •  for touch: pointer events level 2 use implicit capture (for compatibility with touch events) Pointer Events Level 2: Implicit Pointer Capture
  100. /* events related to pointer capture */ foo.addEventListener("gotpointercapture", ... ,

    false) foo.addEventListener("lostpointercapture", ... , false) /* methods related to pointer capture */ element.setPointerCapture(pointerId) element.releasePointerCapture(pointerId) if (element.hasPointerCapture(pointerId)) { ... }
  101. /* example of how to capture a pointer explicitly */

    element.addEventListener('pointerdown', function(e) { this. setPointerCapture(e.pointerId) ; }, false } /* capture automatically released on pointerup / pointercancel or explicitly with releasePointerCapture() */ patrickhlauke.github.io/touch/tests/pointercapture.html
  102. /* cover all cases (hat-tip Stu Cox) */ if (window.PointerEvent)

    { /* bind to Pointer Events: pointerdown, pointerup, etc */ } else { /* bind to mouse events: mousedown, mouseup, etc */ if ('ontouchstart' in window) { /* bind to Touch Events: touchstart, touchend, etc */ } } /* bind to keyboard / click */
  103. /* adding jQuery PEP */ <script src="https://code.jquery.com/pep/0.4.1/pep.js"></script> /* need to

    use custom touch-action attribute, not CSS (yet) */ <button touch-action="none" >...</div>
  104. events fired on tap with PEP pointerover > pointerenter >

    pointerdown > touchstart > pointerup > pointerout > pointerleave > touchend > mouseover > mouseenter > mousemove > mousedown > mouseup > click essentially, relevant Pointer Events before touchstart and touchend
  105. /* Hammer's high-level events example */ var element = document.getElementById('test_el');

    var hammertime = new Hammer(element); hammertime.on("swipe", function(event) { /* handle horizontal swipes */ });
  106. enable touch events even without a touchscreen (to test "naive"

    'ontouchstart' in window code) chrome://flags/#touch-events
  107. Chrome DevTools / Device Mode & Mobile Emulation correctly emulates

    pointer events (with pointerType=="touch" )
  108. no touch emulation, nor touch events + pointer events (like

    on real Windows 10 Mobile) emulation, in Edge/F12 Tools
  109. no concept of hover on touch devices iOS fakes it,

    Samsung Galaxy Note II/Pro + stylus, ...
  110. iOS Developer Library - Safari Web Content Guide - Handling

    Events while this works ok, Safari is the only browser doing it...
  111. Input Device Capabilities •  currently limited usefulness - only has

    firesTouchEvents property •  limited use cases (see Identifying touch events that will trigger a tap / click, Identifying mouse events derived from touch events and Google Developer: Input Device Capabilities) •  easier to switch to Pointer Events (and add PEP)?
  112. myButton.addEventListener('touchstart', addHighlight, false); myButton.addEventListener('touchend', removeHighlight, false); myButton.addEventListener('mousedown', addHighlight, false); myButton.addEventListener('mouseup',

    removeHighlight, false); myButton.addEventListener('click', someFunction, false); /* addHighlight/removeHighlight will fire twice for touch (first for touch, then for mouse compatibility events); can't use e.preventDefault(), as we want to rely on 'click' */
  113. myButton.addEventListener('touchstart', addHighlight, false); myButton.addEventListener('touchend', removeHighlight, false); myButton.addEventListener('mousedown', function(e) { if

    (!e.sourceCapabilities.firesTouchEvents) { addHighlight(e); } } , false); myButton.addEventListener('mouseup', function(e) { if (!e.sourceCapabilities.firesTouchEvents) { removeHighlight(e); } } , false); myButton.addEventListener('click', someFunction, false); /* same function for touch and mouse, but if mouse check if source input fires touch events (i.e. this is a mouse compat event) */
  114. Leap Motion •  requires custom code (JavaScript, Java, C++, ...)

    using proprietary API (e.g. Leap Motion: JavaScript SDK Documentation) •  does not fire touch nor mouse events (third party native apps in Leap Motion App Store available to simulate native mouse) •  (personally find it quite inaccurate and horrible)
  115. /* rough proof of concept that fires programmatic Pointer Events

    for each "pointable" (finger / tool) */ e = new PointerEvent('pointermove', { pointerId: ... , width: ... , height: ... , pressure: ... , tiltX: ... , tiltY: ... , pointerType: 'leap', isPrimary: false, clientX: ... , clientY: ... , screenX: ... , screenY: ... }); /* dispatch event to whatever element is at the coordinates (no support for pointer capture at this stage) */ document.elementFromPoint(x, y).dispatchEvent(e);
  116. •  Matt Gaunt – Touch Feedback for Mobile Sites •

     Jonathan Stark – FastActive •  Stephen Woods – HTML5 Touch Interfaces •  YouTube: Stephen Woods – Responsive HTML5 Touch Interfaces •  Chris Wilson + Paul Kinlan – Touch And Mouse: Together Again For The First Time •  Ryan Fioravanti – Creating Fast Buttons for Mobile Web Applications •  Boris Smus – Multi-touch Web Development •  Boris Smus – Generalized input on the cross-device web •  Boris Smus – Interactive touch laptop experiments
  117. •  Rick Byers + Boris Smus (Google I/O) – Point,

    Click, Tap, Touch - Building Multi-Device Web Interfaces •  Grant Goodale – Touch Events •  W3C – Touch Events Extensions •  Mozilla Developer Network – Touch Events •  WebPlatform.org – Pointer Events •  Rick Byers – The best way to avoid the dreaded 300ms click delay is to disable double-tap zoom •  Chromium Issue 152149: All touch-event related APIs should exist if touch support is enabled at runtime
  118. •  Tim Kadlec – Avoiding the 300ms Click Delay, Accessibly

    •  David Rousset - Unifying touch and mouse [...] •  Microsoft – Pointer events updates (differences between IE10-IE11) •  Patrick H. Lauke – Webseiten zum Anfassen •  Patrick H. Lauke – Drei unter einem Dach: Pointer-Events für Maus, Stylus und Touchscreen •  Patrick H. Lauke – Erweiterte Interaktionsmöglichkeiten mit Touchscreens •  Patrick H. Lauke – Make your site work on touch devices •  Stu Cox – You can't detect a touchscreen
  119. •  Microsoft – Hover touch support (IE10/IE11) •  W3C Media

    Queries Level 4 – pointer •  Stu Cox – The Good & Bad of Level 4 Media Queries •  Peter-Paul Koch – Touch table •  Peter-Paul Koch – Preventing the touch default •  Peter-Paul Koch – Mouse event bubbling in iOS •  YouTube: Edge Conference (Feb 2013 London) – Panel: Input •  Edge Conference (Mar 2014 London) – Panel: Pointers and Interactions •  Trent Walton – Device-Agnostic
  120. •  Stu Cox – The Golden Pattern for Handling Touch

    Input •  Matt Gaunt – ‘Focusing’ on the Web Today •  Mobiscroll – Working with touch events •  Peter-Paul Koch – The iOS event cascade and innerHTML •  Patrick H. Lauke – Make your site work on touch devices •  Scott Jehl (Filament Group) – Tappy: A custom tap event handler •  Yehuda Katz – Touch events on the web are fundamentally unfinished •  Google Developers: A More Compatible, Smoother Touch
  121. •  Andrea Giammarchi – PointerEvents No More •  YouTube: Matt

    Gaunt (Google) - Touch in a Web App? No Problem •  Luke Wroblewski – How to Communicate Hidden Gestures •  David Washington - Designing custom touch interactions •  David Washington - Building pull-to-refresh •  Andy Peatling - JavaScript Pull to Refresh for the Web •  Tilo Mitra – The State of Gestures •  YouTube: Tilo Mitra (YUI) – The State of Gestures
  122. •  Rob Larsen - The Uncertain Web: Pointer Event Polyfill

    and Chrome Fragmentation •  Detlev Fisher - Implications of new input modes (touch, speech, gestures) for the Web Content Accessibility Guidelines •  Ralph Thomas - Towards declarative touch interactions •  Windows Dev Center: Windows desktop applications > Guidelines > Interaction (touch, keyboard, mouse, pen) •  Microsoft Open Technologies - jQuery Adopts Pointer Events
  123. •  jQuery blog - Getting on Point •  IEBlog -

    Pointer Events W3C Recommendation, Interoperable Touch, and Removing the Dreaded 300ms Tap Delay •  Microsoft Open Technologies - Pointer Events is now a W3C Standard •  Patrick H. Lauke (The Paciello Group) - Pointer Events advance to W3C Recommendation •  Jacob Rossi - The Input Shouldn't Matter •  hacks.mozilla.org - Pointer Events now in Firefox Nightly
  124. •  Rick Byers – Interoperability Case Studies at BlinkOn 5

    (touch-action) •  Mozilla Developer Network – Pointer Events •  Christian Saylor – A Touch of Brilliance: Why 3D Touch Matters •  Lukas Mathis – Usability on Mobile Is Getting Worse •  Rocket Insights – Initial thoughts on 3D Touch •  Wiser Coder – Disable “pull to refresh” in Chrome for Android
  125. •  Google Developers / Web Fundamentals: Add touch to your

    site •  Alex Gibson – Different ways to trigger touchcancel in mobile browsers •  BBC Global Experience Language: How to design for touch •  Google BlinkOn 5: Lightning talks / Mustaq Ahmed – Pointer Events in Chrome implementation update •  A Book Apart: Josh Clark – Designing for Touch •  Kickstarter – The Sensel Morph: Interaction Evolved
  126. •  Ruadhán O'Donoghue – The HTML5 Pointer Events API: Combining

    touch, mouse, and pen •  Jordan Staniscia – Hover is dead. Long live hover. •  Jason Grigsby – Four Truths About Input •  Jason Grigsby – Adapting to Input •  David Corbacho – Debouncing and Throttling Explained •  YouTube: Pre-Touch Sensing for Mobile Interaction (Microsoft)
  127. •  YouTube: HTML5DevConf: Jacob Rossi, "Pointer Events, Panning & Zooming,

    and Gestures" •  YouTube: Jacob Rossi, "Pointing Forward" at W3Conf 2013 •  YouTube: Tim Park: Pointing Forward (updated) – JSConf.Asia 2013 •  Flickity – touch, responsive, flickable carousels •  Google Developers / Update: Once Upon an Event Listener •  Google Developers / Update: Improving Scroll Performance with Passive Event Listeners •  Google Developers / Update: Making touch scrolling fast by default
  128. •  Google Developers / Update: Pointing the Way Forward •

     Google Developers / Update: Touch Action Options •  Universal Stylus Initiative (USI) •  Adobe Creative Cloud: Andrew Smyk – Holistic Adaptive Design: Factors to Consider in a Multi-Screen World •  YouTube: Drawboard on Surface Studio with Surface Dial •  AirBar – Touch without a touchscreen •  GitHub: Rafael Pedicini (Rafrex) – Detect It