Chapter 7. Catching Events

Events are fired when certain activity occurs within a web page, including when the page is finished loading. In JavaScript, you can capture these events via “hooks” known as event handlers, which you can then use to call a function or to process some other JavaScript.

Events in JavaScript are also associated with page elements and are not intrinsic to the language itself. In previous chapters, the applications used the onload event handler to call a function when the page was finished loading. The actual event is the load event, which is associated with the browser window object. The onload event handler is triggered when the page is finished loading into the browser window.

To make working with events more challenging, event handling is one aspect of JavaScript that has changed significantly over the years, and is still one area where differences exist among browsers. Luckily, these differences are fairly easy to overcome. Before we discuss cross-browser event handling, though, we’ll take a quick look at the events and when they’re typically activated.

The Events

The events themselves are relatively intuitive to understand. The World Wide Web Consortium (W3C) categorizes events into three distinct areas: user interface (mouse, keyboard), logical (result of a process), and mutation (action that modifies a document). Table 7-1 lists some basic events, their descriptions, and the affected objects.

Table 7-1. Events and affected objects

Event

Description

Affected ...

Get Learning JavaScript, 2nd Edition 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.