5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

HTMLの要素にタッチイベントを実装する

Posted at

個人的に多用するHTMLへのタッチイベント実装方法

タッチイベントはボタンのクリックイベントよりも反応速度が速い場合が多い。

実装準備

まず、HTML要素をidで取得しておく。

var touchPannel = document.getElementById("touchPannel");
//ここに以下のいずれかのコードを記述

実装方法

タッチイベントの種類
・"touchstart"
 指定した要素をタッチしたら関数を実行
・"touchmove"
 指定された要素をタッチし、指を動かすと関数を実行
・"touchend"
 指定された要素をタッチし、指を離すと関数を実行

以下2つの方法を挙げる。

方法1: 

タッチイベント用関数を先に定義("addEventListener"の引数は2つで、一つ目が「イベントの種類」で二つ目が「実行する関数名」)


function touch(e){
  alert("done")
}
touchPannel.addEventListener("touchend",touch);

この方法は、同じ関数を複数の要素にタッチイベントとして実装する場合に便利。

方法2:

要素にタッチイベントを実装("addEventListener"の引数は3つで、一つ目が「イベントの種類」、二つ目が「実行する関数」、三つ目が"false")

touchPannel.addEventListener("touchend",function (event){
  alert("done");
},false)
5
4
0

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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?