From efe9363924b98d14ceb063c7a0a676f754bb1bd1 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sat, 30 Dec 2017 12:52:30 +0200 Subject: [PATCH] Update onUserInputChange.md --- snippets/onUserInputChange.md | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/snippets/onUserInputChange.md b/snippets/onUserInputChange.md index d726c51fb..99f5ac60d 100644 --- a/snippets/onUserInputChange.md +++ b/snippets/onUserInputChange.md @@ -1,23 +1,18 @@ ### onUserInputChange -Will run the callback whenever the user changes their input type (either `mouse` or `touch`). This is useful -if you want to disable certain code depending on if the user is using touch as input or a mouse (including trackpads). +Run the callback whenever the user input type changes (`mouse` or `touch`). Useful for enabling/disabling code depending on the input device. This process is dynamic and works with hybrid devices (e.g. touchscreen laptops). Use two event listeners. Assume `mouse` input initially and bind a `touchstart` event listener to the document. -On `touchstart`, the callback is run and supplied with the current input type as an argument. -Then, add a `mousemove` event listener to listen for two consecutive `mousemove` events firing within 20ms -using `performance.now()` (browsers recently fire them every animation frame). Run the callback and supply the new type -`mouse` as the argument. This process needs to happen dynamically because of hybrid devices (such as a touchscreen laptop), -where the user can switch between either input type at will. +On `touchstart`, add a `mousemove` event listener to listen for two consecutive `mousemove` events firing within 20ms, using `performance.now()`. +Run the callback with the input type as an argument in either of these situations. ```js const onUserInputChange = callback => { let type = 'mouse', lastTime = 0; const mousemoveHandler = () => { const now = performance.now(); - if (now - lastTime < 20) { + if (now - lastTime < 20) type = 'mouse', callback(type), document.removeEventListener('mousemove', mousemoveHandler); - } lastTime = now; }; document.addEventListener('touchstart', () => {