Handle user input change

JavaScript, Browser, Event · Oct 21, 2020

Runs the callback whenever the user input type changes (mouse or touch).

  • Use two event listeners.
  • Assume mouse input initially and bind a 'touchstart' event listener to the document.
  • 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.
const onUserInputChange = callback => {
  let type = 'mouse',
    lastTime = 0;
  const mousemoveHandler = () => {
    const now = performance.now();
    if (now - lastTime < 20)
      (type = 'mouse'),
        callback(type),
        document.removeEventListener('mousemove', mousemoveHandler);
    lastTime = now;
  };
  document.addEventListener('touchstart', () => {
    if (type === 'touch') return;
    (type = 'touch'),
      callback(type),
      document.addEventListener('mousemove', mousemoveHandler);
  });
};
onUserInputChange(type => {
  console.log('The user is now using', type, 'as an input method.');
});

More like this

  • JavaScript Event Handling

    Event handling needs to be done right in JavaScript. Pick up some tips and tricks to create a better user experience.

    Collection · 15 snippets

  • Handle click outside

    Runs the callback whenever the user clicks outside of the specified element.

    JavaScript, Browser · Jan 6, 2021

  • Handle scroll stop

    Runs the callback whenever the user has stopped scrolling.

    JavaScript, Browser · Jan 6, 2021

  • Add multiple listeners

    Adds multiple event listeners with the same handler to an element.

    JavaScript, Browser · Oct 22, 2020