LoginSignup
3
5

More than 1 year has passed since last update.

ボタン連打、連続クリックを止める

Last updated at Posted at 2019-10-04

更新ボタンを連打されAjaxの処理を重複させない為に、処理中にボタンを無効にしたい。
無効時はボタンの色を薄くして、わかるようにする。

処理概要

①クリック時にボタンを無効にし色を変更。

②クリック時に行いたい処理を書く(書き換え、送信処理など)。

③処理完了後、指定時間後にボタンを有効にし色を戻す。
ここでは、仮に処理が1秒程かかるとして、1秒間だけ無効にする。

※しかし、処理完了後にすぐボタンを有効にしたい場合、
setTimeoutを削除する。
詳しくはページ下部の補足

備考

●disabled
クリックできるか true:無効化、false:有効化。

disabledが有効の場合自動で半透明になるので、特にオリジナルのカラーを使用しなければ以下2つは必要ない。
●addClass( )
既存の CSS クラスを追加する場合に使用

●removeClass( )
既存の CSS クラスを削除する場合に使用

ソース

a.html
<script>
$(function(){

  //更新ボタンクリック
  $("#refresh").click(function (event) {
    //ボタンクリック無効化
    if (cancelFlag == false) {
      $("#refresh").prop("disabled", true).addClass("btn-pink");

      //処理内容
        $.ajax({
          url: "https://?????",
          type: "GET",
          success: function () {
            console.log("OK");
          },
        });

      //ボタンクリック有効化
      setTimeout(function () {
        $("#refresh").prop("disabled", false).removeClass("btn-pink");
      }, 1000);
    }
  });

});
</script>

<button id="refresh" class="btn-red">更新</button>
b.css
/*ボタンは赤色*/
.btn-red {
    background-color: #red;
}

/*ボタン無効時はピンク*/
.btn-pink {
    background-color: #pink;

補足

処理終了と同時に有効化したい場合、有効化の部分のsetTimeout()を削除し、処理内容の最後に有効化処理を入れる。
更新終了と同時にボタンを有効化にできる。

a.html
<script>
・・・
        //処理内容
        $.ajax({
          url: "https://?????",
          type: "GET",
          success: function () {
            console.log("OK");
            //ボタンクリック有効化
            $('#refresh').prop('disabled', false).removeClass('sending');
          },
        });
・・・
</script>
(※追記)

chromeでは問題なかったが、
IE(バージョン不明)ではボタン有効化時の.prop('disabled', false)が効いていない
ことが判明。
removeAttr()でボタン無効処理ごと消す。

a.html
<script>
・・・
//ボタンクリック有効化
$('#refresh').removeAttr('disabled').removeClass('sending');
・・・
</script>
3
5
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
3
5