Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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);
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away