addEventListener method

void addEventListener(
  1. String type,
  2. EventListener? callback, [
  3. JSAny options
])

The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.

Common targets are Element, or its children, Document, and Window, but the target may be any object that supports events (such as IDBRequest).

Note: The addEventListener() method is the recommended way to register an event listener. The benefits are as follows:

  • It allows adding more than one handler for an event. This is particularly useful for libraries, JavaScript modules, or any other kind of code that needs to work well with other libraries or extensions.
  • In contrast to using an onXYZ property, it gives you finer-grained control of the phase when the listener is activated (capturing vs. bubbling).
  • It works on any event target, not just HTML or SVG elements.

The method addEventListener() works by adding a function, or an object that implements a handleEvent() function, to the list of event listeners for the specified event type on the EventTarget on which it's called. If the function or object is already in the list of event listeners for this target, the function or object is not added a second time.

Note: If a particular anonymous function is in the list of event listeners registered for a certain target, and then later in the code, an identical anonymous function is given in an addEventListener call, the second function will also be added to the list of event listeners for that target.

Indeed, anonymous functions are not identical even if defined using the same unchanging source-code called repeatedly, even if in a loop.

Repeatedly defining the same unnamed function in such cases can be problematic. (See Memory issues, below.)

If an event listener is added to an EventTarget from inside another listener — that is, during the processing of the event — that event will not trigger the new listener. However, the new listener may be triggered during a later stage of event flow, such as during the bubbling phase.

Implementation

external void addEventListener(
  String type,
  EventListener? callback, [
  JSAny options,
]);