[jquery] How to prevent a double-click using jQuery?

I have a button as such:

<input type="submit" id="submit" value="Save" />

Within jQuery I am using the following, but it still allows for double-clicks:

<script type="text/javascript">

$(document).ready(function () {

    $("#submit").one('click', function (event) {  

Any idea on how I can prevent double-click?

This question is related to jquery double-click

The answer is


/*
Double click behaves as one single click


"It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable."

That way we have to check what is the event that is being executed at any sequence. 

   */
       var totalClicks = 1;

 $('#elementId').on('click dblclick', function (e) {

 if (e.type == "dblclick") {
    console.log("e.type1: " + e.type);
    return;
 } else if (e.type == "click") {

    if (totalClicks > 1) {
        console.log("e.type2: " + e.type);
        totalClicks = 1;
        return;
    } else {
        console.log("e.type3: " + e.type);
        ++totalClicks;
    }

    //execute the code you want to execute
}

});

I have the similar issue. You can use setTimeout() to avoid the double-click.

//some codes here above after the click then disable it

// also check here if there's an attribute disabled

// if there's an attribute disabled in the btn tag then // return. Convert that into js.

$('#btn1').prop("disabled", true);

setTimeout(function(){
    $('#btn1').prop("disabled", false);
}, 300);

You can do something like this to disable submit button when loading a new page with the same form:

$("#btnConfirm").bind("click", function (e) {
  $("#btnConfirm ").css("pointer-events", "none");
});

The submit button could look like this:

<input
    type="submit"
    name="ACMS_POST_Form_Confirm"
    value="confirm"
    id="btnConfirm"
/>

This is my first ever post & I'm very inexperienced so please go easy on me, but I feel I've got a valid contribution that may be helpful to someone...

Sometimes you need a very big time window between repeat clicks (eg a mailto link where it takes a couple of secs for the email app to open and you don't want it re-triggered), yet you don't want to slow the user down elsewhere. My solution is to use class names for the links depending on event type, while retaining double-click functionality elsewhere...

var controlspeed = 0;

$(document).on('click','a',function (event) {
    eventtype = this.className;
    controlspeed ++;
    if (eventtype == "eg-class01") {
        speedlimit = 3000;
    } else if (eventtype == "eg-class02") { 
        speedlimit = 500; 
    } else { 
        speedlimit = 0; 
    } 
    setTimeout(function() {
        controlspeed = 0;
    },speedlimit);
    if (controlspeed > 1) {
        event.preventDefault();
        return;
    } else {

        (usual onclick code goes here)

    }
});

My solution: https://gist.github.com/pangui/86b5e0610b53ddf28f94 It prevents double click but accepts more clicks after 1 second. Hope it helps.

Here is the code:

jQuery.fn.preventDoubleClick = function() {
  $(this).on('click', function(e){
    var $el = $(this);
    if($el.data('clicked')){
      // Previously clicked, stop actions
      e.preventDefault();
      e.stopPropagation();
    }else{
      // Mark to ignore next click
      $el.data('clicked', true);
      // Unmark after 1 second
      window.setTimeout(function(){
        $el.removeData('clicked');
      }, 1000)
    }
  });
  return this;
}; 

"Easy Peasy"

$(function() {
     $('.targetClass').dblclick(false);
});

The solution provided by @Kichrum almost worked for me. I did have to add e.stopImmediatePropagation() also to prevent the default action. Here is my code:

$('a, button').on('click', function (e) {
    var $link = $(e.target);
    if (!$link.data('lockedAt')) {
        $link.data('lockedAt', +new Date());
    } else if (+new Date() - $link.data('lockedAt') > 500) {
        $link.data('lockedAt', +new Date());
    } else {
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();
    }
});

I found that most solutions didn't work with clicks on elements like Labels or DIV's (eg. when using Kendo controls). So I made this simple solution:

function isDoubleClicked(element) {
    //if already clicked return TRUE to indicate this click is not allowed
    if (element.data("isclicked")) return true;

    //mark as clicked for 1 second
    element.data("isclicked", true);
    setTimeout(function () {
        element.removeData("isclicked");
    }, 1000);

    //return FALSE to indicate this click was allowed
    return false;
}

Use it on the place where you have to decide to start an event or not:

$('#button').on("click", function () {
    if (isDoubleClicked($(this))) return;

    ..continue...
});

If what you really want is to avoid multiple form submissions, and not just prevent double click, using jQuery one() on a button's click event can be problematic if there's client-side validation (such as text fields marked as required). That's because click triggers client-side validation, and if the validation fails you cannot use the button again. To avoid this, one() can still be used directly on the form's submit event. This is the cleanest jQuery-based solution I found for that:

<script type="text/javascript">
$("#my-signup-form").one("submit", function() {
    // Just disable the button.
    // There will be only one form submission.
    $("#my-signup-btn").prop("disabled", true);
});
</script>

What I found out was old but working solution on modern browsers. Works for not toggling classes on the double click.

$('*').click(function(event) {
    if(!event.detail || event.detail==1){//activate on first click only to avoid hiding again on double clicks
        // Toggle classes and do functions here
        $(this).slideToggle();
    }
});

just put this method in your forms then it will handle double-click or more clicks in once. once request send it will not allow sending again and again request.

<script type="text/javascript">
    $(document).ready(function(){
            $("form").submit(function() {
                $(this).submit(function() {
                    return false;
                });
                return true;
            }); 
    }); 
</script>

it will help you for sure.


I had a similar issue, but disabling the button didn't fully did the trick. There were some other actions that took place when the button was clicked and, sometimes, button wasn't disabled soon enough and when the user double-clicked, 2 events where fired.
I took Pangui's timeout idea, and combined both techniques, disabling the button and includeding a timeout, just in case. And I created a simple jQuery plugin:

var SINGLECLICK_CLICKED = 'singleClickClicked';
$.fn.singleClick = function () {
    var fncHandler; 
    var eventData;
    var fncSingleClick = function (ev) {
        var $this = $(this);
        if (($this.data(SINGLECLICK_CLICKED)) || ($this.prop('disabled'))) {
            ev.preventDefault();
            ev.stopPropagation();
        }
        else {
            $this.data(SINGLECLICK_CLICKED, true);
            window.setTimeout(function () {
                $this.removeData(SINGLECLICK_CLICKED);
            }, 1500);
            if ($.isFunction(fncHandler)) {
                fncHandler.apply(this, arguments);
            }
        }
    }

    switch (arguments.length) {
        case 0:
            return this.click();
        case 1:
            fncHandler = arguments[0];
            this.click(fncSingleClick);
            break;
        case 2: 
            eventData = arguments[0];
            fncHandler = arguments[1];
            this.click(eventData, fncSingleClick);
            break;
    }
    return this;
}

And then use it like this:

$("#button1").singleClick(function () {
   $(this).prop('disabled', true);
   //...
   $(this).prop('disabled', false);
})

In my case, jQuery one had some side effects (in IE8) and I ended up using the following :

$(document).ready(function(){
  $("*").dblclick(function(e){
    e.preventDefault();
  });
});

which works very nicely and looks simpler. Found it there: http://www.jquerybyexample.net/2013/01/disable-mouse-double-click-using-javascript-or-jquery.html


Just one more solution:

$('a').on('click', function(e){
    var $link = $(e.target);
    e.preventDefault();
    if(!$link.data('lockedAt') || +new Date() - $link.data('lockedAt') > 300) {
        doSomething();
    }
    $link.data('lockedAt', +new Date());
});

Here we save the time of last click as data attribute and then check if previous click was more than 0.3 seconds ago. If it is false (less than 0.3 sec ago), just update last click time, if true, do something.

jsbin


I was able to do this task efficiently by the following way

  1. As soon as the button click handler is called disable the button

  2. Do the necessary operations needed to be done.

  3. Set the disabled property back to false after a couple of seconds using SetTimeout

     $('#btn1).click(function(e){
     $('#btn1').prop("disabled", true);
    
     setTimeout(()=>{
     $('#btn1').prop("disabled", false);
     },2000)
    

This should solve the issue.