liveBook · Manning

Event-handler registration

As explained in Secrets of the JavaScript Ninja, Second Edition

The act of associating a handler with an event target or event type so it runs when the event occurs.

Browser applications become interactive by registering functions that the browser runs when events such as clicks or key presses occur. section 2.3

Two registration approaches are shown:

  • Assign a function to a special property such as onload or onclick. This is straightforward, but allows only one handler for a particular event, so a new assignment can overwrite an earlier one. section 2.3.2
  • Call addEventListener with an event type and handler function. It allows multiple handlers for the same event. section 2.3.2
Listing 2.3. Registering event handlers
<script>
  document.body.addEventListener("mousemove", function() {        #A 
    var second = document.getElementById("second");        
    addMessage(second, "Event: mousemove");            
  });

  document.body.addEventListener("click", function(){             #B
    var second = document.getElementById("second");        
    addmessage(second, "Event: click");            
  });
</script>

This example registers mousemove and click handlers on the document body; each adds an event message to a list. section 2.3.2

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines property assignment and addEventListener, notes overwrite limits, and stops short of explaining event dispatch.
Examples
Uses window load, body click, and mousemove handlers, including handlers that append event messages to a list.
What you can do after
Apply event-handler registration with addEventListener or event properties to make browser interfaces interactive.
How it connects
Connects event-handler registration to browser event handling, the DOM, and event listeners.

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.