Question

I am using code from this post and the double click prevention works, however the button still does not respond to preventDefault

Can anyone lend a hand please.

js:

var myBtn = $('.myLink');
var handler = function(e){
    e.preventDefault();
    console.log("prevent 2x click");
    $(this).unbind('click');
    setTimeout(function(){ myBtn.click(handler); }, 500);
}
myBtn.click(handler);

html:
<a class='myLink' href="#">my link to click</a>

Was it helpful?

Solution

Reason is that when you unbind the handler(which has preventDefault) and in the small period of time one more click comes in it doesn't prevent the default behavior. So you can attach a dedicated handler to prevent default and unbind the handler that just does your other logic. Try this way:

var myBtn = $('.myLink');

var handler = function(e){
    $(this).unbind('click', handler); //unbind only your handler
    setTimeout(function(){
            myBtn.click(handler); }
    , 500);
}

myBtn.click(preventDefault); //have this bound to the anchor to prevent the default behavior always

myBtn.click(handler);

function preventDefault(e){
   e.preventDefault();
}

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top