Event Bubbling and Event Capture

Today’s article is going to be a quick insight into what is meant when developers talk about event bubbling and capturing. Although there is a lot to write about this topic, Peter-Paul Koch explains most of it at Quirksmode: Event Ordering. He does not mention Safari in his writeup, but it also supports both bubbling and capture.

Article updated on Nov. 26, 2011

This article is ancient. It was revisited in Event Bubble & Capture Phases.

Event capture and bubbling are a result of how browser’s worked at the end of 1990s. When two elements, one the child of the other, have the same JavaScript event attached to them, the browser determines which event happens first. Netscape decided that the events should flow from the parent down to the child node (capture), while IE decided that the event should flow from the child to the parent node (bubble). Most modern browsers (except IE) now support both models, but implicitly use the bubble model. If you want your code to be browser independent, you should only use the bubble model. Here is an example of what I mean:

Example 1: Nodes

<div id="outerDiv" onclick="someFunctionA(){}">
	<div id="innerDiv" onclick="someFunctionB(){}"></div>

According to the bubble event model, if innerDiv is clicked then its onclick event happens first, then the outerDiv onclick event happens, assuming you havent stopped the bubbling of the event. Conversely, according to the capture event model, if innerDiv is clicked, then the outerDiv onclick event happens first, followed by the innerDiv onclick (assuming you dont stop the event from continuing the capture phase). Obviously, this these two models could lead to very different results.

Fortunately, you can safely assume that you are only dealing with the bubbling model, unless you explicitly define your event handlers to fire using the capture model. I strongly advise against doing that unless you are coding something that you do not want IE to support and absolutely require the capture model. For more information, please see PPK&rsquot;s article that I mentioned above.

Lastly, I am going backpacking in Kings Canyon for the rest of this week and until Wednesday of next week. Unfortunately, my laptop, a portable power generator, and a satellite uplink are all a little to heavy for me to carry, so I will not be blogging again until next Friday. Enjoy your Holiday, if you have one, and when I come back we can continue our exploration of the wonderful world of JavaScript.