jQuery in Action
Understanding the browser event models
93
Let's once again change the example of listing 4.1 to use the more advanced
event model. We'll concentrate only on the click event type; this time, we'll estab-
lish three click event handlers on the image element. The new example code can
be found in the file chapter4/dom.2.events.html and is shown in listing 4.3.
lish three click event handlers on the image element. The new example code can
be found in the file chapter4/dom.2.events.html and is shown in listing 4.3.
<html>
<head>
<title>DOM Level 2 Events Example</title>
<script type="text/javascript"
src="../scripts/jquery-1.2.1.js">
</script>
<script type="text/javascript">
$(function(){
var element = $('#vstar')[0];
element.addEventListener('click',function(event) {
say('Whee once!');
},false);
element.addEventListener('click',function(event) {
say('Whee twice!');
},false);
element.addEventListener('click',function(event) {
say('Whee three times!');
},false);
});
function say(text) {
$('#console').append('<div>'+text+'</div>');
}
</script>
</head>
<body>
<img id="vstar" src="vstar.jpg"/>
<div id="console"></div>
</body>
</html>
This code is simple but clearly shows how we have the ability to establish multiple
event handlers on the same element for the same event type--something we were
not able to do easily with the Basic Event Model. In the ready handler
event handlers on the same element for the same event type--something we were
not able to do easily with the Basic Event Model. In the ready handler
b
for the
page, we grab a reference to the image element and then establish three event
handlers for the click event.
handlers for the click event.
Loading this page into a standards-compliant browser (not Internet Explorer)
and clicking the image result in the display shown in figure 4.3.
Listing 4.3 Establishing event handlers with the DOM Level 2 Model
Establishes three
event handlers!
event handlers!
b