How to Cancel Event Bubbling: Demo
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
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 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 See also: |
Copyright © 1999-2011, JavaScripter.net.