The DOM event flow
The DOM introduces a new concept for detecting events and assigning
corresponding event handlers to react to them. Naturally, it also supports
the 2 conventional techniques discussed earlier.
In order to fully understand and appreciate this new method, we must
first understand how events are handled in the DOM.
-A roundtrip ticket- event capture and event bubbling
The DOM interprets all user action very differently from the user. To
you, clicking on a link is just that, but to the DOM, an entire process is
invoked that takes the action on a trip around the block and back. Ok,
more explanation is definitely needed.
Let's take the simple user action of moving the mouse over a link as an
example. To the DOM, the following events in fact took place, and in that
order:
1) You moved your mouse over the document
2) You moved your mouse over any tags containing the target <A> tag
3) You moved your mouse over the <A> tag in question
No, we're not quite yet done. From here the event then travels back:
4) You moved your mouse over any tags containing the target <A> tag
5) You moved your mouse over the document. (the end).
Yes, the DOM likes to get very technical. Using a diagram, here's what
just happened:
Mouse over document
-->Mouse over any containment tags of <A> --> Mouse over
destination <A> -->
Mouse over any containment tags of <A> --> Mouse over document
The above "roundtrip" model is used by the DOM to interpret most
events. We call the event as it travels to the intended element (part in
blue) event capture, and as it travels back event bubble.
-Event Capture
So, event capture basically refers to the process of an event as it
travels to its destination element. Actually, it further refers to the
ability to "capture", or intercept this event.
If event capture sounds suspiciously familiar, it should. NS4 has long
supported event capture, though the syntax:
element.captureEvents()
In other words, when you click on a link in NS4 for example, this event
first travels through the document, then incrementally downwards to all
containing elements of the link until eventually reaching the link itself.
-Event bubble
Event bubble is the exact opposite of event capture, and
points to the traveling upwards of an event from the source element to the
topmost, or document. IE4 revolutionized event handling by being the first
major browser to support event bubble. An event such as clicking on a link
causes it to travel upwards, visiting all of the link's container tags
until eventually reaching the top of the document source.
Consider the following HTML code:
<table onClick="alert('Hello!')">
<b><a href="#">This is some text</a></b>
</table>
Here we define an onClick event handler inside the TABLE.
With event bubbling, merely clicking on the containing link fires this
event (and subsequently the alert message), since the event traverses
upwards from A to B and eventually reaching TABLE.
|