DOM - Event Listener

About

An event listener is an object that executes code for an event

An event listener observe a specific event and consists of:

  • type (a string, the event name)
  • callback (null or an EventListener object)
  • capture (a boolean, initially false)
  • passive (a boolean, initially false)
  • once (a boolean, initially false)
  • signal (null or an AbortSignal object)
  • removed (a boolean for bookkeeping purposes, initially false)

Ref

Example

var button = document.getElementById("the-button");
button.addEventListener("click", function () { console.log("Stop Pocking me !"); }, false);
<button id="the-button">Poke ?</button>

Order

General rules:

  • listeners are called in the order they were registered.
  • for handler, because there is only one listener by handler, the listener handler order is the first time, the handler is set to a non-null value.

This example demonstrates this rules.

  • The demo select a button and add listener for the click event
    • via the addEventListener function
    • and a handler (javascript property and html attribute)
var button = document.getElementById("startButton");
// an listener with a callback
button.addEventListener("click", function () { addOutputAfter("1 - Callback") }, false);
// the first handler definition (it will not print because the definition is overwritten with another definition later)
button.onclick = function () { addOutputAfter("2 - Event Handler First definition (idl way)"); }; 
// another listener
button.addEventListener("click", function () { addOutputAfter("3 - Callback") }, false);
// a second handler definition that will overwrite the first one
button.setAttribute("onclick", "addOutputAfter('4 - Event Handler last definition (on attribute)')"); 
  • The HTML with two buttons controls
<button id="startButton">Start Demo</button>
<button id="clearButton">Clear</button>
<div id="output"></div>
  • Result: If the start Button is clicked, the code will add 3 texts (and not 4)
    • 2 from the addEventListener function
    • 1 for the event handler with multiple definition, to demonstrate that:
      • the last code defined is executed
      • at the position of the first definition

The official order definition: The order of event listeners for a particular event type will always be:

  • first the event listeners registered with addEventListener() before the first time an event handler was set to a non-null value,
  • then the callback of the an event handler that is currently set, if any (non null)
  • and finally the event listeners registered with addEventListener() after the event handler was set the first time to a non-null value.

Management

EventListener

addEventListener(type, callback, options)
  • Remove: Event listeners can be removed by utilizing the removeEventListener() method, passing the same arguments than when they were created
removeEventListener(type, callback, options)

handler

Documentation / Reference


Powered by ComboStrap