liveBook · Manning

Handler

As explained in Vanilla Web

An event listener is a callback registration that causes code to run when a specified event occurs.

An event handler is a function that runs when a specified event occurs. Browser events report interactions such as clicks and form changes, as well as updates such as a page becoming hidden. Attach a handler to a DOM node to respond without repeatedly checking for changes. section 6.2.13

An `onclick`-style property is convenient for a quick hook, but assigning it again replaces the previous handler. Prefer `addEventListener` when multiple handlers or options such as `capture`, `passive`, or `once` are needed. Keep the function reference if it must later be removed with `removeEventListener`. section 6.2.13

function onScroll() {
  console.log(window.scrollY);
}
window.addEventListener("scroll", onScroll, { passive: true });

// ... later
window.removeEventListener("scroll", onScroll);

A scroll listener uses the passive option and is later removed using the same function reference. section 6.2.13

Events can travel down the DOM tree in the capture phase and back up in the bubble phase. A handler can inspect `target` and `currentTarget` to distinguish where an event began from the node handling it. Use `preventDefault()` only when the browser’s usual action should be canceled; propagation controls are separate. section 6.2.13

How Vanilla Web covers it

How deep it goes
Explains registration choices, listener options, removal, propagation, targets, and default-action control through native DOM APIs.
Examples
Uses click and scroll handlers, a capture-and-bubble diagram, a list click listener, and a dispatched custom event.
What it assumes
Assumes familiarity with JavaScript functions and DOM nodes while defining event listeners and explaining propagation.
What you can do after
Apply it via `addEventListener` to register, configure, and remove browser event handlers.
How it connects
Connects handlers to DOM nodes, event propagation, default browser actions, and custom events.

Also explained in

Compare how 29 books explain handler →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Vanilla Web. The section links point to the parts of the book it draws on.