liveBook · Manning

addEventListener

As explained in Secrets of the JavaScript Ninja, Second Edition

A DOM method for registering an event listener on an event target without replacing existing listeners for the same event type.

Browser applications use event handlers to respond to actions such as clicks and mouse movement. addEventListener registers a handler with the browser for a chosen event. section 2.3 section 2.3.2

Why use addEventListener instead of assigning an event property?

  • An event property such as onclick holds one handler, so assigning another can overwrite the previous one. addEventListener lets you register multiple handlers and specify an event type and function. 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 separate handlers for mousemove and click on the page body; each adds a labeled message to a list. section 2.3.2

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines registration, contrasts property assignment, and demonstrates multiple event types; leaves event-processing flow for later.
Examples
Demonstrates body mousemove and click handlers that append labeled messages to a list.
What you can do after
Apply the DOM method to register multiple handlers for specified events.
How it connects
Connects event handlers with the DOM and event-property assignment.

Also explained in

Compare how 2 books explain addEventListener →

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.