34

I'm writing a little jQuery extension that prevents a user from double clicking on a link.

$.fn.preventDoubleClick = function() {
    return this.click(function() {
        var $t = $(this)
            , retVal = $t.data('active')  // check the internal flag
        ;
        if (retVal || retVal === undefined) { // if ON...
            $t.data('active', false);  // set the internal flag to OFF
            setTimeout(function() {
                $t.data('active', true);
            }, 1000);  // after 1 second, set the internal flag to ON
            console.log("allowed");
            return true;
        } else {  // if OFF...
            console.log("blocked");
            return false;
        }
    });
};

the problem is that if there are other click event handlers on the elements, they still fire:

$('#myLink').click(function() {
    console.log("Clicked");
});
$('#myLink').preventDoubleClick();

And now when you double click the link, I get this in my log:

allowed
clicked
blocked
clicked

So basically, I need the click function inside preventDoubleClick to stop all the other event handlers from firing. How can I do this?

nickf
  • 537,072
  • 198
  • 649
  • 721
  • 1
    Also, "preventDoubleClick" is a misleading name, afterall it's not prevented -the user still double clicks - you just block it from firing the event, I think... – James Apr 14 '09 at 06:28

2 Answers2

50

Thanks to Adam's link, I was able to see the function I needed: stopImmediatePropagation().

fregante
  • 29,050
  • 14
  • 119
  • 159
nickf
  • 537,072
  • 198
  • 649
  • 721
  • 6
    This also works without jQuery, here's the documentation for the standard [stopImmediatePropagation()](https://developer.mozilla.org/en-US/docs/Web/API/event.stopImmediatePropagation) – fregante Mar 31 '14 at 16:27
7

I believe you're looking for event.stopPropagation

EDIT: turns out this was not the correct option for Nick's purposes. Please see his answer.

Community
  • 1
  • 1
Adam Alexander
  • 15,132
  • 5
  • 42
  • 41