liveBook · Manning

Handler

As explained in Secrets of the JavaScript Ninja, Third Edition

A function invoked in response to an event or request to perform associated application logic.

An event handler is a function the browser invokes when its associated event occurs. Registering handlers connects events such as key presses to application behavior, giving a web interface interactivity. section 4.3 section 4.3.2

A handler participates in the browser’s event-processing cycle:

  • Register a function for an event, typically with addEventListener on a DOM element. section 4.3.2
  • When an event occurs, the browser queues it; when it reaches the front, the browser runs its associated handler if one exists. section 4.3.1
  • Handlers run one at a time. Long-running work can delay other events and make the application unresponsive. section 4.3.1

Reacting to a key press

Register a keydown handler on document with document.addEventListener("keydown", (evt) => { ... }). The handler can use evt.key to identify the pressed key and append a message to the page. Because keydown bubbles, a handler on document can also respond when typing in an input. section 4.3.2 section 4.1

Listing 4.2 Registering event handlers
document.addEventListener("DOMContentLoaded", () => {  #A
  appendToEventList('Event "DOMContentLoaded" fired'); #A
});                                                    #A
 
document.addEventListener("keydown", (evt) => {                       #B
  appendToEventList(`Event "keydown" fired with key = "${evt.key}"`); #B
});                                                                   #B

Compare registrations for DOMContentLoaded and keydown, including how the key handler reads the event’s key. section 4.3.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines registration and queued, single-threaded execution, while deferring event-loop details and bubbling and capturing.
Examples
Uses DOMContentLoaded and keydown handlers to append event messages, including the pressed key.
What you can do after
Apply event handling by registering functions with addEventListener and reading event data in a keydown handler.
How it connects
Connects event handlers to the DOM, event queues, and event bubbling.

Also explained in

Compare how 29 books explain handler →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.