liveBook · Manning

Handler

As explained in Secrets of the JavaScript Ninja, Second Edition

A callable routine that runs in response to a dispatched event.

An event handler is a function the browser calls when its associated event occurs. Registering handlers lets a browser application respond to user actions and update the DOM. section 2.3 section 13.3

When events arrive, handlers run in sequence:

  • The browser queues events in occurrence order; the event loop runs the associated handler, and later events wait until it finishes. section 2.3.3
  • A handler can receive an event object with details such as the target element; `this` refers to the element where the handler was registered. section 13.3

A click handler

Register a function with `addEventListener("click", handler)` on a button. When the button is clicked, the browser calls the function and passes it an event object. section 13.3

Listing 13.6. Registering event handlers
<button id="myButton">Click</button>
<script>
  const myButton = document.getElementById("myButton");
  myButton.addEventListener("click", function myHandler(event){   #A
    assert(event.target === myButton,                             #B
          "The target of the event is also myButton");            #B

    assert(this === myButton,                                     #C
           "The handler is registered on myButton");              #C
  });
</script>

See a button click handler registered with `addEventListener`, including checks of the event target and `this`. section 13.3

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains registration, event data, and serial queue execution, while deferring event propagation details.
Examples
Uses mousemove and click callbacks that append messages, plus a button click handler.
What you can do after
Apply it via addEventListener to respond to clicks and inspect the event object.
How it connects
Connects handlers to event listeners, event objects, event queues, the event loop, and DOM updates.

Also explained in

Compare how 22 books explain handler →

Related concepts

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