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 ...

Get JavaScript Web Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.