简体   繁体   中英

jQuery Disable a button and change its style for a few seconds

I'm working on an audio player and I'd like to disable the "NEXT" button for 3 seconds, and make it slightly transparent during that same amount of time.

The disable function seems to work, but when I'm adding the change of style to it then nothing works anymore.

Here is what I got so far :

HTML

<i class="fa fa-step-forward fa-fw" id="fwd"></i>

jQuery

var clickLock = 0;

$('#fwd').on('click', function(){
    if (clickLock == 0) {
        clickLock = 1;

        setTimeout(function(){  
           clickLock = 0;
        }, 3000);
    }

});

$(function(){
 $('#fwd').click(function(){
    $(this).addClass('disabled');
    setTimeout(function(){
      $('#fwd').removeClass('disabled');}, 3000);
});

css

.disabled {
  opacity: 0.3;
}

What am I doing wrong ?

Why don't you do it like that:

var clickLock = 0;

$('#fwd').on('click', function(){
    if (clickLock == 0) {
        clickLock = 1;
        $('#fwd').addClass('disabled');

        setTimeout(function(){  
           clickLock = 0;
           $('#fwd').removeClass('disabled');
        }, 3000);
    }
});

What you have works, you're just missing }); at the end of your function that wraps the $.click() handler on #fwd .

If you're working on something and you have a syntax error like this, check your browser console and you should see an error that can point you to the problem.

 var clickLock = 0; $('#fwd').on('click', function() { if (clickLock == 0) { clickLock = 1; setTimeout(function() { clickLock = 0; }, 3000); } }); $(function() { $('#fwd').click(function() { $(this).addClass('disabled'); setTimeout(function() { $('#fwd').removeClass('disabled'); }, 3000); }); }); 
 .disabled { opacity: 0.3; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <i class="fa fa-step-forward fa-fw" id="fwd">click</i> 

You're problem might be that you are binding the disabling click handle before the diviner has loaded. Try moving it to the jQuery ready .

You could drastically simplify your code by using a semantic button element and styling it accordingly.

function disableButton(event) {
  var $button = $(event.target);
  $button.addClass('disabled').prop('disabled', 'disabled');

  setTimeout(function(){  
    $button.removeClass('disabled').prop('disabled', false);
  }, 3000);
}

$(document).ready(function() {
  $('#forward-button').on('click', disableButton);
});

http://jsbin.com/pubemawomu/edit?output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM