Skip to Main Content
JavaScript Web Applications
book

JavaScript Web Applications

by Alex MacCaw
August 2011
Intermediate to advanced content levelIntermediate to advanced
276 pages
6h 37m
English
O'Reilly Media, Inc.
Content preview from JavaScript Web Applications

Chapter 2. Events and Observing

Events are at the core of your JavaScript application, powering everything and providing the first point of contact when a user interacts with your application. However, this is where JavaScript’s unstandardized birth rears its ugly head. At the height of the browser wars, Netscape and Microsoft purposely chose different, incompatible event models. Although they were later standardized by the W3C, Internet Explorer kept its different implementation until its latest release, IE9.

Luckily, we have great libraries like jQuery and Prototype that smooth over the mess, giving you one API that will work with all the event implementations. Still, it’s worth understanding what’s happening behind the scenes, so I’m going to cover the W3C model here before showing examples for various popular libraries.

Listening to Events

Events revolve around a function called addEventListener(), which takes three arguments: type (e.g., click), listener (i.e., callback), and useCapture (we’ll cover useCapture later). Using the first two arguments, we can attach a function to a DOM element, which is invoked when that particular event, such as click, is triggered on the element:

var button = document.getElementById("createButton");

button.addEventListener("click", function(){ /* ... */ }, false);

We can remove the listener using removeEventListener(), passing the same arguments we gave addEventListener(). If the listener function is anonymous and there’s no reference to it, it can’t ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaScript Application Design

JavaScript Application Design

Nicolas Bevacqua
JavaScript: Best Practice

JavaScript: Best Practice

James Kolce, Moritz Kroger, Ivan Curic, Samier Saeed, Jeff Mott, M. David Green, Craig Buckler

Publisher Resources

ISBN: 9781449308216Errata PageSupplemental Content