Detect Javascript Swipe for Touch Screens and Mouse

Lightweight Javascript function to detect swipes left, right, up, down.

Javascript:

(function() {
  function dir() {
    a = x - x1, b = y - y1;
    if (!(parseInt(Math.sqrt(a * a + b * b), 10) < THRESHOLD)) {
      if (x1 - x > Math.abs(y - y1)) {
        return "left";
      }
      if (x - x1 > Math.abs(y - y1)) {
        return "right";
      }
      if (y1 - y > Math.abs(x - x1)) {
        return "up";
      }
      if (y - y1 > Math.abs(x - x1)) {
        return "down";
      }
    } else {
      return "none";
    }
  }
  THRESHOLD = 15;
  x = y = x1 = y1 = 0;
  recordedTime = (new Date).getTime();
  document.documentElement.addEventListener("touchstart", function(a) {
    50 < (new Date).getTime() - recordedTime && (x = parseInt(a.changedTouches[0].pageX, 10), y = parseInt(a.changedTouches[0].pageY, 10), recordedTime = (new Date).getTime());
  }, !1);
  document.documentElement.addEventListener("touchend", function(a) {
    x1 = x;
    y1 = y;
    x = parseInt(a.changedTouches[0].pageX, 10);
    y = parseInt(a.changedTouches[0].pageY, 10);
    document.getElementById("direction").innerHTML = dir();
    recordedTime = (new Date).getTime();
  }, !1);
  document.documentElement.addEventListener("mousedown", function(a) {
    50 < (new Date).getTime() - recordedTime && (x = a.clientX, y = a.clientY, recordedTime = (new Date).getTime());
  }, !1);
  document.documentElement.addEventListener("mouseup", function(a) {
    x1 = x;
    y1 = y;
    x = a.clientX;
    y = a.clientY;
    document.getElementById("direction").innerHTML = dir();
    recordedTime = (new Date).getTime();
  }, !1);
  document.documentElement.style.userSelect = "none";
})();

HTML:

<!-- 
This is only needed for demonstration purposes.
For production, modify the function dir() to return whatever is need for your app.
-->
<div id="direction"></div>

Swipe the screen left, right, up, or down. The swipe direction shows up in the box below. A swipe direction of "none" indicates the swipe did not meet the threshold.

 
Copyright © Lage.us Website Development | Disclaimer | Privacy Policy | Terms of Use