jQuery in Action
Understanding the browser event models
95
Think back a moment to the example of listing 4.2 where we explored the prop-
agation of the Basic Model events through a
agation of the Basic Model events through a
DOM
hierarchy. In that example we
embedded an image element within two layers of
<div>
elements. Within such a
hierarchy, the propagation of a click event with the
<img>
element as its target
would move through the
DOM
tree as shown in figure 4.4.
Let's put that to the test, shall we? Listing 4.4 shows the code for a page con-
taining the element hierarchy of figure 4.4 (chapter4/dom.2.propagation.html).
<html id="greatgreatgrandpa">
<head>
<title>DOM Level 2 Propagation Example</title>
<script type="text/javascript"
src="../scripts/jquery-1.2.1.js">
</script>
<script type="text/javascript">
$(function(){
$('*').each(function(){
var current = this;
this.addEventListener('click',function(event) {
say('Capture for ' + current.tagName + '#'+ current.id +
' target is ' + event.target.id);
},true);
this.addEventListener('click',function(event) {
say('Bubble for ' + current.tagName + '#'+ current.id +
' target is ' + event.target.id);
},false);
});
});
Listing 4.4 Tracking event propagation with bubble and capture handlers
Figure 4.4 Propagation in the DOM Level 2 Event Model traverses the DOM
hierarchy twice: once from top to target during capture phase and once from
target to top during bubble phase.
hierarchy twice: once from top to target during capture phase and once from
target to top during bubble phase.
Establishes listeners
on all elements
on all elements
b