Posted by triaslama on July 3, 2008
Capturing phase is an event moving down the DOM tree to the element that instantiated event. Bubbling phase occuring after Capturing phase. Bubbling phase begins from the source of the event (e.g. button click) traverses up DOM tree to the root element.
Let’s see the following document structure:
<input type="button" />
When we click the button, the event captured by the document first, then <body> element, <form> element, and finally the <input type=”button” /> element (capturing phase). After that the event moves back, started from button element (button click event handler fired), <form>’s click, <body>’s click, and document click event handler fired (bubbling phase).
For the complete example try the following (evtphases.htm):
Runs the code in the browser and click the button and see what happen. I run the code in my computer, I click the button element, and I get three alert box fired! first ‘Button clicked!’, second ‘Form clicked!’, and ‘Document clicked’ for third!
Well, I just click the button but the click event bubbling and traverses up the DOM tree started from button element, element, element, and finally up to document element.
How if I want to stop the event bubbling? Fortunately we can do that!
Canceling Event Bubbling
Every event object (depend on what the browser is) has the ability for canceling event bubbling. Events in W3C compliant browsers has a method named stopPropagation() to cancel event bubbling. Internet Explorer has cancelBubble propertiy, set the value of this property to true means cancel the event bubbling.
So just change our code for button element to the following:
<input type="button" id="btn" value="Button" onclick="btnClick(event)" />
Now refresh the page and click the button. I run it and only get one alert message (‘Button clicked!’). Yes, we have cancel the event bubbling and make the button as the last element that received the event!