LoginSignup
2
2

More than 5 years have passed since last update.

長押しボタンを作ってみた【初期実装】

Last updated at Posted at 2019-04-13

はじめに

最近のゲームでボタンを長押しを要求するUXがより、それをWebでも使えないかと思い、作ってみました。

作ってみる

さっそく作ります。

長押しボタンの仕様

大きな仕様は以下2つです。

  • 特定の秒数長押しするとアクションが発生する
  • 途中で長押しをやめるとカウントが0に戻る

長押しの検知

マウスイベントには、長押しを検知するイベントがないため、 mousedownmouseupsetIntervel を組み合わせることで長押しを検知しました。

index.html
<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
        <!--
            #button1 {
                width: 50px;
                height: 50px;
                border-radius: 50%;
                border: none;
                background-color: gray;
            }
        -->
        </style>
    </head>
    <body>
        <button id="button1"></button>
        <script>
            (function(){
                var LIMIT = 10;
                var timer;
                var count = 0;
                var button1 = document.getElementById('button1');

                var start = function () {
                    console.log("mousedown");
                    if (!timer) {
                        timer = setInterval(counter, 100);
                    } 
                }
                var stop = function () {
                    console.log("mouseup");
                    clearInterval(timer);
                    timer = 0;
                    count = 0;
                }

                button1.addEventListener('mousedown', start, false);
                button1.addEventListener('mouseup', stop, false);

                var counter = function(){
                    console.log(count++);
                    if (count > 9) {
                        console.log('OK');
                        clearInterval(timer);
                        timer = 0;
                        count = 0;
                    }
                }
            })();
        </script>
    </body>
</html>

簡単に説明すると、mousedown で呼ばれる処理で、setIntervalをセットし、 counter 処理を100ms毎に実行。
countが10以上になると処理を停止するという流れです。

右クリック禁止とmouseoutイベント時の処理

処理のクオリティをあげるために、ぐちゃぐちゃ操作していたら、右クリックと mouseout イベント時に処理が正常に動かなくなっため、制御をいれました。

index.html
  var button1 = document.getElementById('button1');
  // 右クリック禁止
  button1.oncontextmenu = function () {
    return false;
  }
・・・
  button.addEventListener('mousedown', start, false);
  button.addEventListener('mouseup', stop, false);
  // mouseoutイベント追加
  button.addEventListener('mouseout', stop, false);
・・・

進捗の表示

長押し中にどのくらいの進捗なのかを表示するために、 秒数の表示とdiv要素を追加しました。

完成

ソースコードは以下githubにあがっています。
https://github.com/takuhou/smart-ui/blob/master/index.html

ただ、これだとクオリティがいまいちなので、
UXやモジュールとして提供するために、追加実装を続けております。

今回の記事で書いたプログラミングの様子をYoutube上にアップロードしておりますので、是非ご覧ください。

【実況】長押しボタンをプログラミング【初期実装】
えんじにぁ〜TV

2
2
1

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
2