view web/swipe/swipe.html @ 1059:8f56ec592d39

Added worst example.
author Oleksandr Gavenko <gavenkoa@gmail.com>
date Mon, 27 Mar 2017 00:41:51 +0300
parents 3c227fd5d1c1
children
line wrap: on
line source
<!DOCTYPE html>
<html>
<head>
  <title>Swipe events</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <meta charset="utf-8"/>
  <style>
    h1 {
      text-align: center;
    }
    #answer {
      text-align: center;
      color: brown;
    }
    #swipe-area {
      position: relative;
      width: 320px;
      height: 320px;
      margin: 1rem auto;
      border: 1px solid green;
      background-color: cornsilk;
    }
    .msg {
      position: absolute;
      display: inline;
      width: 100px;
      height: 2rem;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
    }
  </style>
</head>
<body>
  <h1>Swipe events</h1>

  <div id="answer">unknown</div>
  
  <div id="swipe-area"><div class="msg">Swipe area</div></div>

  <script>
    function direction(x, y) {
      var sensitivity = Math.min(document.documentElement.clientWidth, document.documentElement.clientHeight);
      var sensitivity = sensitivity*sensitivity / 100;
      if (x*x + y*y < sensitivity)
        return null;
      if (Math.abs(x) < Math.abs(y)) {
        if (y > 0)
          return "down";
        else
          return "up";
      } else {
        if (x > 0)
          return "right";
        else
          return "left";
      }
    }

    var ANSWER = document.getElementById("answer");
    var swipeStartX = null;
    var swipeStartY = null;
    var swipeEndX = null;
    var swipeEndY = null;
    function swapStart(ev) {
      swipeStartX = ev.touches[0].pageX;
      swipeStartY = ev.touches[0].pageY;
      ev.preventDefault();
    }
    function swapMove(ev) {
      swipeEndX = ev.touches[0].pageX;
      swipeEndY = ev.touches[0].pageY;
      ev.preventDefault();
    }
    function swapEnd(ev) {
      var swipeX = swipeEndX - swipeStartX;
      var swipeY = swipeEndY - swipeStartY;
      var dir = direction(swipeX, swipeY);
      if (dir) {
        ANSWER.innerHTML = dir;
      } else {
        ANSWER.innerHTML = "undetected";
      }
      swipeStartX = null;
      swipeStartY = null;
      ev.preventDefault();
    }
    function swapCancel(ev) { }

    var area = document.getElementById("swipe-area");
    area.addEventListener("touchstart", swapStart, false);
    area.addEventListener("touchmove", swapMove, false);
    area.addEventListener("touchend", swapEnd, false);
    area.addEventListener("touchcancel", swapCancel, false);
  </script>
</body>
</html>