Bubbles, capture, and all that jazz

DOM events aren’t the funniest things in the World, but they’re rather handy, and (at least if you ask me) the handling of them is pretty well thought out and gives a nice flexibility.

I have, however, run into a little interesting gotcha. When you register two different event listeners on a DOM element, one for the capturing phase and one for the bubbling phase, and you trigger an event with the element as it’s target, the order in which the listeners are registered matters.

My expectation was that the capturing event listener is always triggered first regardless of the order the listeners were registered.

But it seems that at least in the latest version of both Google Chrome and Mozilla Firefox the registration order matters.

I have created a very simple example on jsFiddle, that enables you to test it in your browser. Just click in each of the two boxes.

My result in both Chrome and Firefox is, as you can see.. Unexpected!

What happens in Chrome and Firefox?

Whether this is intentional, incidental or just a result of a poor specification, I am not entirely sure of. It seems to me, though, that the DOM Level 3 Events specification defines the capturing phase to always precede the bubbling phase no matter where it happens in the DOM tree.