Event Bubbling and Event Propagation: Demo
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
element of the page). Finally, the event ends up being handled at the highest level in the DOM hierarchy, the
element itself (provided that your
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.
|In this demo,
event handlers change the background color of their respective elements. The event handlers are defined at four levels:
(1) the document body
(2) the table element:
(3) table row elements:
(4) individual table cells:
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
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
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
is triggered too
which colorizes the entire page once again! To avoid unintended consequences like this, you can cancel event bubbling.