How to avoid double clicking with jQuery

There has been always one troubling issue regarding web forms and user interaction: when the user double clicks the submit button. Detecting and preventing it or disabling the button is an expensive operation in terms of computing. Fortunately, jQuery has a neat solution. As usual.

Enter one function. This function will simply unbind the click event from an object after it has been clicked. It is really that simple. All you need to pass to one() is the event that you want to bind/unbind and a handler function to execute when the event is triggered:

[js]
jQuery(‘#submit-form’).one(‘click’, function() {
alert(‘Hold your horses, girl!’);
});
[/js]

or you can simply hide the button, like the following example

Click me once!

The code for the example above is
[js]
jQuery(document).ready(function(){
jQuery(‘#oncebutton’).one(‘click’, function() {
jQuery(this).slideUp();
});
});
[/js]

Read more about one() in the documentation for jQuery.

12 thoughts on “How to avoid double clicking with jQuery”

  1. Vinny, remember to wrap the function with
    jQuery(document).ready(function(){
    //code goes here
    });

    as shown in the second snippet.
    Just in case, the first image isn’t an working example, ok? it’s merely illustrative.

  2. Ah but what happens if they’re submitting a form that errors? They’ll need to resubmit but the button will have no click event anymore

    1. Of course Jenna, but this is only an example. You could disable the button before validation, and if there are errors you could enable click again. However, you could also validate the form while it’s being filled using, for example, the Validation plugin for jQuery.

  3. 是的防守对方士大夫士大夫撒的撒的士大夫撒的发生的撒的撒的撒的撒的撒的ss地方s的
    士大夫
    sdf sdf
    撒的
    士大夫
    撒的f撒的
    撒的
    士大夫
    士大夫
    士大夫
    士大夫
    士大夫

  4. Hey

    This does the same thing as unbind(‘click’); but i have a problem here… say you do one() or unbind the click… then if you try to do toggle or slideToggle() it wont work any more… very fustrating.. then if you do a unbind() then a bind() you get a jQuery Internal error .. this has wasted my day.. not your post.. but this stupid click crap

Leave a Reply to Cordyceps Cancel reply