Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop further event handlers on an element

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?

like image 427
nickf Avatar asked Apr 14 '09 06:04

nickf


People also ask

How do you stop stopPropagation?

To stop an event from further propagation in the capturing and bubbling phases, you call the Event. stopPropation() method in the event handler. Note that the event. stopPropagation() method doesn't stop any default behaviors of the element e.g., link click, checkbox checked.

Which method prevent the event from bubbling up the DOM tree preventing any parent handlers from being notified of the event?

stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed.

Can you add multiple event handlers to elements?

You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements. i.e the window object.


2 Answers

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

like image 54
nickf Avatar answered Sep 23 '22 10:09

nickf


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.

like image 24
Adam Alexander Avatar answered Sep 22 '22 10:09

Adam Alexander