↑
Main Page
Types of Events
When the button is clicked on this page, three alerts are displayed one after another:
“input”
,
“body”
,
and
“html”
. This happens, of course, because the event bubbles up from the
<input/>
element to
<body/>
and then to
<html/>
. If, however, you stop the event propagation at the button, things change:
<html onclick=”alert(‘html’)”>
<head>
<title>Stopping Event Propagation Example</title>
<script type=”text/javascript” src=”detect.js”></script>
<script type=”text/javascript”>
function handleClick(oEvent) {
alert(“input”);
if (isIE) {
oEvent.cancelBubble = true;
} else {
oEvent.stopPropagation();
}
}
</script>
</head>
<body onclick=”alert(‘body’)”>
<input type=”button” value=”Click Me” onclick=”handleClick(event)” />
</body>
</html>
When this example is executed and the button is clicked, you only see the
“input”
alert and none of
the others because the propagation has been stopped. In order to do this correctly, you make use of the
browser detection code from the last chapter.
You may also notice that the
<input/>
element passes in the
event
object as an argument to the
handleClick()
function. This works in all browsers because the
event
object is created as soon as
the event happens and is a global variable at this point.
Types of Events
The events that occur in a browser can be grouped into several specific types, depending on the object
the event is fired from and what triggered the event to fire. The DOM specification defines the following
event groups:
?
Mouse Events are fired when the user uses the mouse to perform certain actions.
?
Keyboard Events are fired when the user types on the keyboard.
?
HTML Events are fired when certain changes occur to the browser window or specific client-
server interaction occurs.
?
Mutation Events are fired when a change occurs to the underlying DOM structure.
279
All about Events
12_579088 ch09.qxd 3/28/05 11:39 AM Page 279
Free JavaScript Editor
Ajax Editor
©
→