22
24

More than 5 years have passed since last update.

JavascriptでHTML要素の長押しを検知して何かする

Last updated at Posted at 2018-11-23

WebサイトやUI作成時に使えるようメモ。JavascriptのバージョンはES2015。

1 サンプル

上矢印を長押ししている間、数値を1ずつカウントアップ、下矢印は同様にカウントダウン。

See the Pen wQmyaO by snst.lab (@snst-lab) on CodePen.


2 関数の定義


/**
* @function HTMLElement.prototype.hold 要素の長押しを検知し、何かする
*/
if(!HTMLElement.prototype.hold){
    Object.defineProperty(HTMLElement.prototype, 'hold', {
        configurable: true,
        enumerable: false,
        writable: true,
        /**
        * @function callback 長押し判定後に行われる何かの処理
        * @int holdtime 長押し判定時間のしきい値(ミリ秒)
        */
        value: function(callback,holdtime) {
            this.addEventListener('mousedown', function (event) {
                event.preventDefault();
                callback(); //event.preventDefaultでクリック等のイベントが解除されてしまうので、要素初タッチ時にも処理を行うようcallbackを設置しておく。
                let time = 0;
                const interval = setInterval(function(){
                  time += 100;
                  if(time > holdtime){
                    callback();
                  }
                },100);
                this.addEventListener('mouseup', function (event) {
                  event.preventDefault();
                  clearInterval(interval);
                });
            });
        }
    });
}

スマホやタブレットのタッチにも反応させる場合は、上記のイベントリスナでmousedown→touchstart、mouseup→touchendとしたものをvalue()メソッド内に追加する。

3 使い方

HTML

<div class='number'>100</div>
<div class='arrow up'></div>
<div class='arrow down'></div>

Javascript

const number = document.querySelector('.number');
const up = document.querySelector('.up');
const down  = document.querySelector('.down');

//上矢印を長押ししている間、数値をカウントアップ
up.hold(()=>{number.textContent = +number.textContent+1;},1000);
//下矢印を長押ししている間、数値をカウントダウン
down.hold(()=>{number.textContent = +number.textContent-1;},1000);
22
24
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
22
24