0
0

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 3 years have passed since last update.

JaveScriptでタップイベントを拾う

Last updated at Posted at 2020-01-30

意外と情報がなかったので。

ES6版

tap_es6.js
element.addEventListener("touchstart", function(...args) {
    const [element, event] = args;
    let isTouchMove = false;
    element.addEventListener("touchend", (e) => {
        if (!isTouchMove) {
            /* logic */
        }
    }, {once: true})
    element.addEventListener("touchmove", (e) => {
        isTouchMove = true;
    }, {once: true})
}.bind(null, element))

normal版

tap.js
element.addEventListener("touchstart", function(...args) {
    const [element, event] = args;
    let isTouchMove = false;
    element.addEventListener("touchend", (e) => {
        if (!isTouchMove) {
            /* logic */
        }
    }, {once: true})
    element.addEventListener("touchmove", (e) => {
        isTouchMove = true;
    }, {once: true})
}.bind(null, element))

解説

touchendの中にタップしたときのロジックを載せてしまうと、要素を触りながら要素外へ移動して離したときもタップしたことになってしまう。
つまりユーザが一度要素を触ってしまったらキャンセル不可能になってしまう。
それを防ぐためにtouchstartを拾ったらその中でtouchendとtouchmoveを拾うようにした。
もしtouchendよりまえにtouchmoveを検知したらタップをキャンセルしたとみなして、タップされたときのロジックを実行しない。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?