2
1

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.

javascriptでのダブルクリック制御

Last updated at Posted at 2018-03-07

ググって出てきたコードがどうも納得いかないので書き換えた
dblclickの動きを確認したけど、あの挙動だと使い道がわからない

1回ならシングルクリック
2回以上ならダブルクリックとして扱う

            $('.hoge').on('click', function (e) {

                var obj = this;

                console.log('click!');

                // クリック監視中なら現在のタイマを停止
                var timer_id = -1;
                if (!(isNullOrUndefined($(this).data('timer_id'))) ) {
                    timer_id = Number($(this).data('timer_id'));
                    if (timer_id >= 0) {
                        clearInterval(timer_id);
                    }
                }

                // クリック回数を加算
                var click_count = 0;
                if (isNullOrUndefined($(this).data('click_count'))) {
                    click_count = 0;
                } else {
                    click_count = Number($(this).data('click_count'));
                }
                click_count++;
                
                timer_id = setTimeout(function () {

                    // 連続クリックイベントが終了するとここにくる
                    var count = Number($(obj).data('click_count'));

                    if (count == 1) {
                        console.log('single click!');
                    } else {
                        console.log('double click!');
                    }
                    $(obj).data('timer_id', -1);
                    $(obj).data('click_count', 0);

                }, 250);

                $(this).data('timer_id', timer_id);
                $(this).data('click_count', click_count);
            });
2
1
2

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?