Skip to main content

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

/**
 * onUserInputChange
 *
 * 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.
 *
 * Source: https://www.30secondsofcode.org/js/s/on-user-input-change
 *
 * @param {Function} callback
 * @return {[type]}
 */
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);
  });
};

/**
 * Examples
 */
onUserInputChange((type) => {
  console.log("The user is now using", type, "as an input method.");
});

// ------------------------------------------------------------------
// ES5 version
// ------------------------------------------------------------------

/**
 * onUserInputChange
 *
 * Runs the callback whenever the user input type changes (mouse or touch).
 *
 * Source: https://www.30secondsofcode.org/js/s/on-user-input-change
 *
 * @param {Function} callback
 * @return {[type]} [description]
 */
var onUserInputChange = function (callback) {
  var type = "mouse",
    lastTime = 0;

  var mousemoveHandler = function () {
    var now = performance.now();
    if (now - lastTime < 20)
      (type = "mouse"),
        callback(type),
        document.removeEventListener("mousemove", mousemoveHandler);
    lastTime = now;
  };

  document.addEventListener("touchstart", function () {
    if (type === "touch") return;
    (type = "touch"),
      callback(type),
      document.addEventListener("mousemove", mousemoveHandler);
  });
};

/**
 * Examples
 */
onUserInputChange(function (type) {
  console.log("The user is now using", type, "as an input method.");
});