Help us understand the problem. What is going on with this article?

スマホのスワイプ検知

More than 5 years have passed since last update.

スマホの横スワイプを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;
  }
});
Wataru
オンラインゲームの制作運営会社で働いているフロントエンド側の人間です。 仕事で作ったスクリプトを公開できる形に改変して公開しています!
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした