How to Cancel Event Bubbling: Demo

JavaScript FAQ | Keyboard & Mouse Events FAQ  

Question: How do I cancel event bubbling or stop event propagation?

Answer: Sometimes, event bubbling may have unintended consequences. For example, in the event bubbling demo clicking the Reset button triggers not only the button's own event handler function resetTable(), but also another, higher-level onclick event handler, which has the unintended consequence of colorizing the entire page. This happens because event bubbling does occur by default. If you would like to cancel event bubbling, you can do so within your event handler function. In Internet Explorer, set event.cancelBubble to true. In most other browsers, such as Firefox, Opera, Google Chrome, etc., call the event.stopPropagation() method. You can cancel bubbling in a cross-browser fashion by using the cancelBubble() function, which is used in the following demo.

function cancelBubble(e) {
 var evt = e ? e:window.event;
 if (evt.stopPropagation)    evt.stopPropagation();
 if (evt.cancelBubble!=null) evt.cancelBubble = true;

Demo: click any cell in the table and watch the click event bubbling!

In this demo, which is a modification of the event bubbling demo, onclick event handlers change the background color of their respective elements: individual table cells, table rows, the whole table, and the entire page body. When you click inside table cells, event handlers at the lowest level (table cells) are triggered first, followed by event handlers at higher levels (table rows, then the whole table, then the page body). Each event handler displays a confirm box telling you the level at which the click event is currently handled. You have the option to cancel the event bubbling at each level by choosing Cancel or pressing the Esc key.

If you try to reset the demo by clicking the left Reset button, this has an unintended result of colorizing the entire page body. When you use the right Reset button, its event handler not only resets the table in the demo, but also calls the cancelBubble() function, so there are no unintended consequences.

See also:

  • How do I add an event handler for a page element?
  • How do I prevent the browser's default action in a JavaScript event handler?
  • What is event bubbling?
  • Copyright © 1999-2011,