views:

866

answers:

4

Say I have something like the following to trap the click even of a button:

$("#button_id").click(function() {
  //disable click event
  //do something
  //re-enable click event
}

How do I temporarily disable the click event of the button until the end of the processing of the original click occurs? I basically have the div disappear after the button is clicked, but if the user clicks on the button fast several times, it processes all those clicks before the div gets a chance to disappear. I want to "debounce" the button so that only the first click gets registered before the div disappears.

A: 

This might help.

Another option - to disable whole form on submit using plugin.

Arnis L.
+1  A: 
$("#button_id").click(function() {
  if($(this).data('dont')==1) return;
  $(this).data('dont',1);
  //do something
  $(this).data('dont',0);
}

Remeber that $.data() would work only for items with ID.

Thinker
+2  A: 

If #button_id implies a standard HTML button (like a submit button) you can use the 'disabled' attribute to make the button inactive to the browser.

$("#button_id").click(function() {
    $('#button_id').attr('disabled', 'true');

    //do something

     $('#button_id').removeAttr('disabled');
});

What you may need to be careful with, however, is the order in which these things may happen. If you are using the jquery hide command, you may want to include the "$('#button_id').removeAttr('disabled');" as part of a call back, so that it does not happen until the hide is complete.

[edit] example of function using a callback:

$("#button_id").click(function() {
    $('#button_id').attr('disabled', 'true');
    $('#myDiv').hide(function() { $('#button_id').removeAttr('disabled'); });
});
FerrousOxide
+3  A: 

This is a more idiomatic alternative to the artificial state variable solutions:

$("#button_id").one('click', DoSomething);

function DoSomething() {
  // do something.

  $("#button_id").one('click', DoSomething);
}

One will only execute once (until attached again). More info here: http://docs.jquery.com/Events/one

Dave Ward