LoginSignup
96
85

More than 5 years have passed since last update.

スマホのスワイプ検知

Posted at

スマホの横スワイプをjQueryを使って検知する

ネットで拾ったコードをベースに自分用に書き直したものを公開できる形に変更してます。
mainというidを持つ要素に対して横スワイプを行うとアラートが出るものです。

$(function() {
  $('#main').on('touchstart', onTouchStart); //指が触れたか検知
  $('#main').on('touchmove', onTouchMove); //指が動いたか検知
  $('#main').on('touchend', onTouchEnd); //指が離れたか検知
  var direction, position;

  //スワイプ開始時の横方向の座標を格納
  function onTouchStart(event) {
    position = getPosition(event);
    direction = ''; //一度リセットする
  }

  //スワイプの方向(left/right)を取得
  function onTouchMove(event) {
    if (position - getPosition(event) > 70) { // 70px以上移動しなければスワイプと判断しない
      direction = 'left'; //左と検知
    } else if (position - getPosition(event) < -70){  // 70px以上移動しなければスワイプと判断しない
      direction = 'right'; //右と検知
    }
  }

  function onTouchEnd(event) {
    if (direction == 'right'){
      alert('右だよ');
    } else if (direction == 'left'){
       alert('左だよ');
    }
  }

  //横方向の座標を取得
  function getPosition(event) {
    return event.originalEvent.touches[0].pageX;
  }
});
96
85
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
96
85