Can text nodes receive events?
One of the most annoying things that developers discovered when the first DOM-compliant browser, Netscape 6, was released had to do with events. Due to the new DOM event flow model, text nodes could receive events. The result was utterly confusing. Suppose you had the following code:
<div id="myDiv">Click Me</div>
If an event handler was assigned to this <div/>
, and then the text “Click Me” was clicked, the event would fire on the text node. Keeping strictly to the letter of the DOM law, this makes sense, since events are supposed to be fired on the deepest part of the DOM tree that was clicked. However, this confused everyone because it’s not the way we were used to thinking about events. I even put a warning in the events chapter of Professional JavaScript to be aware of the issue.
As I’m getting around to rewriting the events chapter for the second edition, I decided to try this out again. To my surprise, I’m not able to get events to fire on text nodes in any DOM-compliant browser (Opera, Safari, or Firefox). When I click on the <div/>
element in the previous example, I get all indications that the event is firing on the <div/>
element itself, not on the text node.
So now I’m a bit confused. Was the Netscape 6 implementation faulty or are today’s browsers faulty? Did common sense overrule the specification? Please keep in mind that I’m certainly not complaining about this, this is the way it should be. I’m just curious as to when this issue was “fixed” and if it’s possible for text nodes to receive events anymore. Anyone with any insights?
A few other oddities about events I’ve noticed:
- Opera prior to 9.5 doesn’t fire events on the event target in the capture phase. According to this post, this was intentional and is the way the spec should be even though other browsers allow it. Apparently Opera got tired of fighting that battle and has given in with version 9.5 to firing events on the event target during the capturing phase.
- Opera’s event bubbling appears to be very confused. Events bubbling up through the page hit
window
before they hitdocument
. - Internet Explorer has the correct scope for event handlers defined using the DOM Level 0 method of property assignment but not when using
attachEvent()
.
Man, events are fun!
Disclaimer: Any viewpoints and opinions expressed in this article are those of Nicholas C. Zakas and do not, in any way, reflect those of my employer, my colleagues, Wrox Publishing, O'Reilly Publishing, or anyone else. I speak only for myself, not for them.