jquery スマホのタッチ終了のイベントを取得する

jquery スマホのタッチ終了のイベントを取得する

jqueryで、スマホのタッチ終了のイベントを取得するサンプルコードを記述してます。 「on」メソッドに「touchend」を使用してます。

環境

  • OS windows10 pro 64bit
  • jquery 3.6.0
  • Apache 2.4.43
  • ブラウザ chrome 101.0.4951.67

スマホのタッチ終了のイベントを取得

スマホのタッチ終了のイベントを取得するには、「on」メソッドに「touchend」を指定します。

$('要素を指定').on('touchend', function() {
    // 処理
})

以下は、指定した要素「id=”img”」をタッチすると、画像が変更されて、タッチが終了すると元の画像に戻るサンプルコードとなります。

※デザインは「semantic-ui」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- semantic.css  -->
  <link rel="stylesheet" type="text/css"
    href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
  <script src="http://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>
<style>
  body>.grid {
    height: 100%;
  }

  .fields {
    margin-top: 50px;
  }
</style>
<script>

$(function () {

  // タッチ終了イベント
  $('#img').on('touchend', function () {

    $('#img').attr('src', 'hoge.jpg')

  })

  // タッチ開始イベント
  $('#img').on('touchstart', function () {

    $('#img').attr('src', 'sample.jpg')

  })

})

</script>

<body>

  <div class="ui center aligned grid">

    <img id="img" class="ui rounded image fields" src="hoge.jpg">

  </div>
</body>

</html>

タッチで画像が変更されていることが確認できます。

また、以下のようにアロー関数を使用して記述することも可能です。
※アロー関数を使用するとthisの挙動が異なります。

$(() => {

 // タッチ終了イベント
  $('#img').on('touchend', () => {

    $('#img').attr('src', 'hoge.jpg')

  })

  // タッチ開始イベント
  $('#img').on('touchstart', () => {

    $('#img').attr('src', 'sample.jpg')

  })

})