How to Cancel Event Bubbling: Demo
Question: How do I cancel event bubbling or stop event propagation?
, but also another, higher-level
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
. In most other browsers, such as Firefox, Opera, Google Chrome, etc., call the
method. You can cancel bubbling in a cross-browser fashion by using the
function, which is used in the following demo.
Demo: click any cell in the table and watch the
event bubbling! In this demo, which is a modification of the event bubbling demo,
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
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
function, so there are no unintended consequences.