18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 9<br />

Preventing the default behavior for an event<br />

To prevent the default behavior for an event in IE, you must set the returnValue property to false:<br />

oEvent.returnValue = false;<br />

In Mozilla, you just call the preventDefault() method:<br />

oEvent.preventDefault();<br />

You may think, “When would I ever want to prevent the default behavior of an event?” Actually preventing<br />

the default behavior can be helpful in several situations.<br />

First, use it when you want to prevent the user from using the context menu that appears when he or<br />

she right-clicks the page. To do this, you prevent the default behavior of the contextmenu event, by<br />

doing this:<br />

document.body.oncontextmenu = function (oEvent) {<br />

if (isIE) {<br />

oEvent = window.event;<br />

oEvent.returnValue = false;<br />

} else {<br />

oEvent.preventDefault();<br />

}<br />

};<br />

In addition, you may want to prevent the default behavior of text boxes when a key is pressed to reject a<br />

certain character, or forestall a button’s action unless certain criteria are met. This is a very powerful feature<br />

and I discuss it further later in the book.<br />

Stopping event propagation (bubbling)<br />

To prevent the event from propagating/bubbling in IE, you must set the cancelBubble property to true:<br />

oEvent.cancelBubble = true;<br />

In Mozilla, you just call the stopPropagation() method:<br />

oEvent.stopPropagation ();<br />

Stopping the event propagation prevents the event handlers for the other objects in the event flow from<br />

being executed. Consider this example:<br />

<br />

<br />

Event Propagation Example<br />

<br />

<br />

<br />

<br />

<br />

278

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!