jQuery Multiple Event Handlers - How to Cancel?

Josh Stodola picture Josh Stodola · Mar 17, 2009 · Viewed 36k times · Source

I have two functions bound to a click event at two different times (using jQuery). The order in which they are fired is significant. They are firing in the correct order. The problem is, when the first function returns false, the second function is still firing!

How can I properly cancel the event?

Example code:

$(document).click(function() { 
  alert('a');
  return false;
});

$(document).click(function() {
  alert('b');
});

You will still see the "b" alert message when clicking the page. This is unacceptable!

Answer

Ken Browning picture Ken Browning · Mar 17, 2009

Use the stopImmediatePropagation function of the jQuery event object.

Keeps the rest of the handlers from being executed. This method also stops the bubbling by calling event.stopPropagation().

$(document).click(function(event) { 
  alert('a');
  event.stopImmediatePropagation();
  return false;
});

$(document).click(function() {
  alert('b');
});