Swipe Support

Add swipe support to your project with this code

HTML

<h1>Swipe Inside the Box</h1>
<div id="box">
  <h1></h1></div>

CSS

h1 {
  text-align: center;
  font-size: 24px;
}

body {
  background: SkyBlue;
}

#box {
  width: 300px;
  height: 300px;
  background: #eef;
  margin: 30px auto;
}

#box h1 {
  padding-top: 120px;
}

JavaScript

var time = 1000, // allow movement if < 1000 ms (1 sec)
  range = 50, // swipe movement of 50 pixels triggers the swipe

  target = $('#box'),
  x = 0,
  t = 0,
  touch = "ontouchend" in document,
  st = (touch) ? 'touchstart' : 'mousedown',
  mv = (touch) ? 'touchmove' : 'mousemove',
  en = (touch) ? 'touchend' : 'mouseup';

target
  .bind(st, function(e) {
    // prevent image drag (Firefox)
    e.preventDefault();
    t = (new Date()).getTime();
    x = e.originalEvent.touches ? e.originalEvent.touches[0].pageX : e.pageX;
  })
  .bind(en, function(e) {
    t = 0;
    x = 0;
  })
  .bind(mv, function(e) {
    e.preventDefault();
    var newx = e.originalEvent.touches ? e.originalEvent.touches[0].pageX : e.pageX,
      r = (x === 0) ? 0 : Math.abs(newx - x),
      // allow if movement < 1 sec
      ct = (new Date()).getTime();
    if (t !== 0 && ct - t < time && r > range) {
      if (newx < x) {
        // swipe left code here
        target.find('h1').html('Swipe Left').fadeIn();
        setTimeout(function() {
          target.find('h1').fadeOut();
        }, 1000);
      }
      if (newx > x) {
        // swipe right code here
        target.find('h1').html('Swipe Right').fadeIn();
        setTimeout(function() {
          target.find('h1').fadeOut();
        }, 1000);
      }
      t = 0;
      x = 0;
    }
  });