06.07.2017 Views

Mastering JavaScript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8<br />

These are two completely opposite views and implementations of how browsers<br />

handled events. To end this madness, World Wide Web Consortium (W3C) decided<br />

a wise middle path. In this model, an event is first captured until it reaches the<br />

target element and then bubbles up again. In this standard behavior, you can choose<br />

in which phase you want to register your event handler—either in the capturing<br />

or bubbling phase. If the last argument is true in addEventListener(), the event<br />

handler is set for the capturing phase, if it is false, the event handler is set for the<br />

bubbling phase.<br />

There are times when you don't want the event to be raised by the parents if it was<br />

already raised by the child. You can call the stopPropagation() method on the<br />

event object to prevent handlers further up from receiving the event. Several events<br />

have a default action associated with them. For example, if you click on a URL link,<br />

you will be taken to the link's target. The <strong>JavaScript</strong> event handlers are called before<br />

the default behavior is performed. You can call the preventDefault() method on<br />

the event object to stop the default behavior from being triggered.<br />

These are event basics when you are using plain <strong>JavaScript</strong> on a browser. There is<br />

a problem here. Browsers are notorious when it comes to defining event-handling<br />

behavior. We will look at jQuery's event handling. To make things easier to manage,<br />

jQuery always registers event handlers for the bubbling phase of the model. This<br />

means that the most specific elements will get the first opportunity to respond to<br />

any event.<br />

jQuery event handling and propagation<br />

jQuery event handling takes care of many of these browser quirks. You can focus on<br />

writing code that runs on most supported browsers. jQuery's support for browser<br />

events is simple and intuitive. For example, this code listens for a user to click on any<br />

button element on the page:<br />

$('button').click(function(event) {<br />

console.log('Mouse button clicked');<br />

});<br />

Just like the click() method, there are several other helper methods to cover almost<br />

all kinds of browser event. The following helpers exist:<br />

• blur<br />

• change<br />

• click<br />

• dblclick<br />

[ 195 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!