jQuery in Action
Understanding the browser event models
89
<html id="greatgreatgrandpa">
<head>
<title>DOM Level 0 Events 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. onclick = function(event) {
if (!event) event = window.event;
var target = (event.target) ?
event.target : event.srcElement;
say('For ' + current.tagName + '#'+ current.id +
' target is ' + target.id);
}
});
});
function say(text) {
$('#console').append('<div>'+text+'</div>');
}
</script>
</head>
<body id="greatgrandpa">
<div id="grandpa">
<div id="pops">
<img id="vstar" src="vstar.jpg"/>
</div>
</div>
<div id="console"></div>
</body>
</html>
We do a lot of interesting things in the changes to this page. First, we remove any
handling for the mouseover event so that we can concentrate on the click event.
We also embed the image element that will serve as the target for our event exper-
iment in a couple of nested
handling for the mouseover event so that we can concentrate on the click event.
We also embed the image element that will serve as the target for our event exper-
iment in a couple of nested
<div>
elements to place the image element deeper
within the
DOM
hierarchy. We also give almost every element in the page a spe-
cific and unique
id
--even the
<body>
and
<html>
tags!
We retain the console and its
say()
utility function for the same reporting pur-
poses used in the previous example.
Listing 4.2 Events propagating from the point of origin to the top of the DOM tree
Selects every
element on the page
element on the page
b
Applies onclick handler to
every selected element
every selected element
c