↑
Main Page
Preventing the default behavior for an event
Preventing the default behavior for an event
To prevent the default behavior for an event in IE, you must set the
returnValue
property to
false
:
oEvent.returnValue = false;
In Mozilla, you just call the
preventDefault()
method:
oEvent.preventDefault();
You may think, “When would I ever want to prevent the default behavior of an event?” Actually pre-
venting the default behavior can be helpful in several situations.
First, use it when you want to prevent the user from using the context menu that appears when he or
she right-clicks the page. To do this, you prevent the default behavior of the
contextmenu
event, by
doing this:
document.body.oncontextmenu = function (oEvent) {
if (isIE) {
oEvent = window.event;
oEvent.returnValue = false;
} else {
oEvent.preventDefault();
}
};
In addition, you may want to prevent the default behavior of text boxes when a key is pressed to reject a
certain character, or forestall a button’s action unless certain criteria are met. This is a very powerful fea-
ture and I discuss it further later in the book.
Stopping event propagation (bubbling)
To prevent the event from propagating/bubbling in IE, you must set the
cancelBubble
property to
true
:
oEvent.cancelBubble = true;
In Mozilla, you just call the
stopPropagation()
method:
oEvent.stopPropagation ();
Stopping the event propagation prevents the event handlers for the other objects in the event flow from
being executed. Consider this example:
<html onclick=”alert(‘html’)”>
<head>
<title>Event Propagation Example</title>
</head>
<body onclick=”alert(‘body’)”>
<input type=”button” value=”Click Me” onclick=”alert(‘input’)” />
</body>
</html>
278
Chapter 9
12_579088 ch09.qxd 3/28/05 11:39 AM Page 278
Free JavaScript Editor
Ajax Editor
©
→