javascript 画面をタッチされたイベントを取得する

javascript 画面をタッチされたイベントを取得する

javascriptで、touchstartイベントを使用して画面をタッチされたイベントを取得するサンプルコードを記述してます。

環境

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

touchstart使い方

touchstartを使うと、タッチが開始された瞬間を取得することが可能です。

window.addEventListener("touchstart", function (event) {
  //処理を記述
});

実際に実行してみます。

window.addEventListener("touchstart", function (event) {
  console.log(event.type)
});

実行結果

また、javascript部は引数を1文字にして、windowオブジェクトを省略すると少し短くコードを記述することも可能です。関数もアロー関数を使用できます。

addEventListener("touchstart", (e) => {
  console.log(e.type)
});

「ontouchstart」を使用しても、同じ結果となります。

ontouchstart = (e) => {  console.log(e.type) };

サンプルコード

以下は、画面がタッチされた際にテキストを表示して、タッチが離れたら別のテキストを表示するサンプルコードとなります。

※cssには「bootstrap material」を使用してます。

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

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
  <link rel="stylesheet"
    href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css"
    integrity="sha384-wXznGJNEXNG1NFsbm0ugrLFMQPWswR3lds2VeinahP8N0zJw9VWSopbjv2x7WCvX" crossorigin="anonymous">
</head>
<style>
  .main {
    margin: 0 auto;
    margin-top: 300px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 25px;
  }
</style>
<script>

  // タッチイベント
  window.addEventListener("touchstart", function (event) {

    document.getElementById('txt').textContent = "タッチされました";

  });

  // タッチが離れた際のイベント
  window.addEventListener("touchend", function (event) {

    document.getElementById('txt').textContent = "タッチが外れました";

  });
  
</script>

<body>
  <div class="main">
    <div id="txt" class="alert alert-primary" role="alert"></div>
</body>

</html>

イベントが取得されて処理が実行されていることが確認できます。