Chapter 6. Catching Events

Events let you know when a user is doing something or when a page has loaded. Catching and handling events lets your code do the right thing at the right time, serving the users of your programs.

Regardless of why they happen or how they’re implemented, events in JavaScript are associated with objects and are not intrinsic to the language itself. Typically, when working with browsers, events are related to the DOM implemented in each browser.

There is a default behavior associated with each event, but events can be used to modify functionality or add additional functionality. Extending the event behavior can be managed within the (X)HTML tag for the object, or in a separate JavaScript code block or file.

The events themselves are fairly intuitive. The W3C (World Wide Web Consortium) categorizes events into three distinct areas: user interface (mouse, keyboard), logical (result of a process), and mutation (action that modifies a document). The basic events, affected objects, and descriptions are listed in Table 6-1.

Table 6-1. Events and affected objects

EventDescriptionObject(s)
abort When image is prevented from loadingAn image element
blur,focusWhen object loses or receives focusApplicable to window and form elements
change When selection changesApplicable to form elements where value changes and after element loses focus
click, doubleclick (dblclick)Clicking or double clicking (two clicks in rapid succession) with mouseMost page elements
contextmenu ...

Get Learning JavaScript 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.