javascript ontouchendでタッチ終了のイベントを取得する

javascript ontouchendでタッチ終了のイベントを取得する

javascriptで、ontouchendを使用して、タッチ終了のイベントを取得するサンプルコードを掲載してます。ブラウザはchromeのデバックモードを使用しています。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.134

ontouchend使い方

ontouchendを使用すると、タッチ終了のイベントを取得することが可能です。

/* html内で利用 */
<タグ ontouchend ="イベント">

/* js内で利用 */
object.ontouchend = function(){ イベント };

ontouchend使い方(html内での使用例)

<div ontouchend="hoge()" style="width: 200px; padding: 20px; margin-bottom: 10px; border: 1px dashed #333333;">
  <p>Hello javascript</p>
</div>

<script>

'use strict';

function hoge() {
  console.log('タッチ終了');
}

</script>

ontouchend使い方(js内での使用例)

<div id="main" style="width: 200px; padding: 20px; margin-bottom: 10px; border: 1px dashed #333333;">
  <p>Hello javascript</p>
</div>

<script>

'use strict';

document.getElementById('main').ontouchend = function(){ 
  console.log('タッチ終了');
};

</script>

実行結果は、「タッチ」が終了すると「タッチ終了」と表示されます。

また、以下のコードを、

document.getElementById('main').ontouchend = function(){ 
  console.log('タッチ終了');
};

document.getElementByIdの省略化と関数をアロー化して、簡潔に記述することもできます。

main.ontouchend = () => {
  console.log('タッチ終了');
};

addEventListener

addEventListenerに登録しても、同じ結果となります。

<div id="main" style="width: 200px; padding: 20px; margin-bottom: 10px; border: 1px dashed #333333;">
  <p>Hello javascript</p>
</div>

<script>

'use strict';

document.getElementById("main").addEventListener ( 
  "touchend", function(){ console.log('タッチ終了')} 
);

</script>

子要素

「ontouchend」や「addEventListener」で「touchend」を指定しても、どちらも子要素でタッチ終了イベントが発生すると、イベントが取得されます。

<div id="main" style="padding: 10px; margin-bottom: 10px; border: 1px dashed #333333;">
    hello javascript!!
    <p id="sub" style="padding: 10px; margin-bottom: 10px; border: 1px dashed #f00606;">hello javascript!!</p>
</div>

<script>

'use strict';

main.ontouchend = () => {
  console.log('親タッチ終了');
};

sub.ontouchend = () => {
  console.log('子タッチ終了');
};

</script>

実行結果

サンプルコード

以下は、
要素にタッチしてタッチが終了した回数をカウントして、カウントした数を表示する
サンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

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

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>

<script>

  let count = 0;

  const hoge = () => {

    count++;

    result.innerHTML = `タッチ終了の回数${count}`;

  }

  window.onload = () => {

    sample.ontouchend = () => { hoge() };

  }

</script>

<body>
  <div class="container mx-auto my-56 w-64 px-4">

    <div id="sample" class="flex justify-center">
      <p id="result" class="bg-gradient-to-r from-green-400 to-blue-500 text-white py-2 px-4 rounded-full mb-3 mt-4">カウント</p>      
    </div>

  </div>
</body>

</html>

カウントされていることが確認できます。