Monday, July 19, 2010

w3c browsers fire bubble listeners before capture listeners

In w3c browsers, the event object's eventPhase property may indicate when it is in capture or bubble mode with a 1 or 3, respectively. A value of 2 indicates that the event object is "at" or processing the target node. However, when the eventPhase is 2, the event's mode is fuzzy.

I discovered this while seeking to branch a handler function's execution based on the mode. My handler not only had trouble distinguishing the mode for the target node, the eventPhase was actually 2 twice. Once at the end of an event's capture mode, and again at the start of it's bubble mode (since both end and begin at the target node). It seems that modern browsers are equally confused.

More often than not, w3c browsers will trigger bubble listeners before capture listeners for the target node - as if the browser too can not distinguish the mode. You can preview this odd behavior in a demo at As usual, do share your results for your browser(s), as a comment to this blog entry. So far, though nowhere near consistent, Firefox performs as expected for a few form elements.

I doubt this is a bug, but rather it is by design. After all, there are only three phases. To explicitly signal an event's mode and location, as it traverses the DOM, requires four values. Plus, no document requires that browsers execute listeners in the order they were assigned... The problem is that historically, w3c browsers have done a pretty good job of executing listeners in the order they were assigned.

Still, even as a bug, it's one most developers will not encounter. Observing best practices (like event delegation), and considering common interface requirements, few will ever assign a capture listener to a target node. As well, listener order matters less on the target node, since the event is neither capturing nor bubbling at that moment, and thus all listeners would execute. Technically, w3c browsers are not behaving badly.

Thus, my issue is with the addEventListener() method. It's "capture" parameter implies that a given function will execute in one of two modes (capture or bubble), and capture listeners execute before bubble listeners. I fear, when it comes to the target node, passing any capture value to this method, equates to "either".


No comments:

Post a Comment