Update onUserInputChange.md

This commit is contained in:
Angelos Chalaris
2017-12-30 12:52:30 +02:00
committed by GitHub
parent 628ab06674
commit efe9363924

View File

@ -1,23 +1,18 @@
### onUserInputChange ### onUserInputChange
Will run the callback whenever the user changes their input type (either `mouse` or `touch`). This is useful 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).
if you want to disable certain code depending on if the user is using touch as input or a mouse (including trackpads).
Use two event listeners. Assume `mouse` input initially and bind a `touchstart` event listener to the document. 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. On `touchstart`, add a `mousemove` event listener to listen for two consecutive `mousemove` events firing within 20ms, using `performance.now()`.
Then, add a `mousemove` event listener to listen for two consecutive `mousemove` events firing within 20ms Run the callback with the input type as an argument in either of these situations.
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.
```js ```js
const onUserInputChange = callback => { const onUserInputChange = callback => {
let type = 'mouse', lastTime = 0; let type = 'mouse', lastTime = 0;
const mousemoveHandler = () => { const mousemoveHandler = () => {
const now = performance.now(); const now = performance.now();
if (now - lastTime < 20) { if (now - lastTime < 20)
type = 'mouse', callback(type), document.removeEventListener('mousemove', mousemoveHandler); type = 'mouse', callback(type), document.removeEventListener('mousemove', mousemoveHandler);
}
lastTime = now; lastTime = now;
}; };
document.addEventListener('touchstart', () => { document.addEventListener('touchstart', () => {