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




























