Event Bubbling and Event Propagation: Demo

JavaScript FAQ | Keyboard & Mouse Events FAQ  

Question: What is event bubbling?

Answer: The concept of event bubbling was introduced to deal with situations where a single event, such as a mouse click, may be handled by two or more event handlers defined at different levels of the Document Object Model (DOM) hierarchy. If this is the case, the event bubbling process starts by executing the event handler defined for individual elements at the lowest level (e.g. individual hyperlinks, buttons, table cells etc.). From there, the event bubbles up to the containing elements (e.g. a table or a form with its own event handler), then up to even higher-level elements (e.g. the BODY element of the page). Finally, the event ends up being handled at the highest level in the DOM hierarchy, the document element itself (provided that your document has its own event handler).

The term event propagation is often used as a synonym of event bubbling. However, strictly speaking, event propagation is a wider term: it includes not only event bubbling but also event capturing. Event capturing is the opposite of bubbling (events are handled at higher levels first, then sink down to individual elements at lower levels). Event capturing is supported in fewer browsers and rarely used; notably, Internet Explorer prior to version 9.0 does not support event capturing.

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

[For a full reset, reload the page]
In this demo, onclick event handlers change the background color of their respective elements. The event handlers are defined at four levels:
(1) the document body <BODY onclick="handleBODY()" ...>
(2) the table element: <TABLE id=tb1 onclick="handleTABLE(event,this.id)" ...>
(3) table row elements: <TR id=tr1 onclick="handleTR(event,this.id)">
(4) individual table cells: <TD id=td11 onclick="handleTD(event,this.id)">
When you click inside table cells, event handlers at the lowest level (4) are triggered first, followed by event handlers at higher levels (3), (2), (1), in this order. Each event handler displays an alert message box telling you the level at which the click event is currently handled. The execution is paused until you dismiss the alert box.

If you try to reset the demo by clicking the Reset button, the button's event handler function resetTable() works as expected (the background colors are reverted to white for the table and the entire page body). However, due to event bubbling, a higher-level event handler function handleBody() is triggered too - which colorizes the entire page once again! To avoid unintended consequences like this, you can cancel event bubbling.

Copyright © 1999-2011, JavaScripter.net.