EventTarget: addEventListener() method
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
XMLHttpRequest
).
Note:
The
addEventListener()
method is the
recommended
way to register an event listener. The benefits are as follows:
onXYZ
property, it gives you finer-grained control of the phase when the listener is activated (capturing vs. bubbling).
addEventListener()
works by adding a function, or an object that implements
EventListener
, 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.
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.
Syntax
addEventListener(type, listener)
addEventListener(type, listener, options)
addEventListener(type, listener, useCapture)
Parameters
-
listener
The object that receives a notification (an object that implements the
-
optionsOptional
An object that specifies characteristics about the event listener. The available
options are:
-
captureOptional
A boolean value indicating that events of this type will be dispatched
to the registered
-
onceOptional
A boolean value indicating that the
-
passiveOptional
A boolean value that, if
-
signalOptional -
useCaptureOptional
A boolean value indicating whether events of this type will be dispatched to
the registered
-
wantsUntrustedOptional Non-standard A Firefox (Gecko)-specific parameter. Iftrue, the listener receives synthetic events dispatched by web content (the default isfalsefor browser chrome andtruefor regular web pages). This parameter is useful for code found in add-ons, as well as the browser itself.
A case-sensitive string representing the event type to listen for.
Event
interface) when an event of the specified type occurs. This must
be
null
, an object with a
handleEvent()
method, or a JavaScript
function
. See
The event listener callback
for details on the callback itself.
listener
before being dispatched to any
EventTarget
beneath it in the DOM tree. If not specified, defaults to
false
.
listener
should be invoked at most once after being added. If
true
, the
listener
would be automatically removed when invoked. If not specified, defaults to
false
.
true
, indicates that the function
specified by
listener
will never call
preventDefault()
. If a passive listener
does call
preventDefault()
, the user agent will do nothing other than
generate a console warning. If not specified, defaults to
false
– except that in browsers other than Safari, defaults to
true
for the
wheel
,
mousewheel
,
touchstart
and
touchmove
events. See
Improving scrolling performance with passive listeners
to learn more.
An
AbortSignal
. The listener will be removed when the given
AbortSignal
object's
abort()
method is called. If not specified, no
AbortSignal
is associated with the listener.
listener
before
being dispatched to
any
EventTarget
beneath it in the DOM tree. Events that are bubbling
upward through the tree will not trigger a listener designated to use capture. Event
bubbling and capturing are two ways of propagating events that occur in an element
that is nested within another element, when both elements have registered a handle for
that event. The event propagation mode determines the order in which elements receive
the event. See
DOM Level 3 Events
and
JavaScript Event order
for a detailed explanation.
If not specified,
useCapture
defaults to
false
.
Note:
For event listeners attached to the event target, the event is in the target phase, rather than the capturing and bubbling phases.
Event listeners in the
capturing
phase are called before event listeners in any non-capturing phases.
Return value
None (
undefined
).
Usage notes
The event listener callback
The event listener can be specified as either a callback function or
an object whose
handleEvent()
method serves as the callback function.
The callback function itself has the same parameters and return value as the
handleEvent()
method; that is, the callback accepts a single parameter: an
object based on
Event
describing the event that has occurred, and it
returns nothing.
For example, an event handler callback that can be used to handle both
fullscreenchange
and
fullscreenerror
might look like this:
function eventHandler(event) {
if (event.type === "fullscreenchange") {
/* handle a full screen toggle */
} else {
/* handle a full screen toggle error */
Safely detecting option support
In older versions of the DOM specification, the third parameter of
addEventListener()
was a Boolean value indicating whether or not to use
capture. Over time, it became clear that more options were needed. Rather than adding
more parameters to the function (complicating things enormously when dealing with
optional values), the third parameter was changed to an object that can contain various
properties defining the values of options to configure the process of removing the event
listener.
Because older browsers (as well as some not-too-old browsers) still assume the third
parameter is a Boolean, you need to build your code to handle this scenario
intelligently. You can do this by using feature detection for each of the options you're
interested in.
For example, if you want to check for the
passive
option:
let passiveSupported = false;
try {
const options = {
get passive() {
// This function will be called when the browser
// attempts to access the passive property.
passiveSupported = true;
return false
;
window.addEventListener("test", null, options);
window.removeEventListener("test", null, options);
} catch (err) {
passiveSupported = false;
This creates an options object with a getter function for the
passive property; the getter sets a flag,
passiveSupported, to true if it gets called. That
means that if the browser checks the value of the passive property on the
options object, passiveSupported will be
set to true; otherwise, it will remain false. We then call
addEventListener() to set up a fake event handler, specifying those
options, so that the options will be checked if the browser recognizes an object as the
third parameter. Then, we call removeEventListener() to clean up after
ourselves. (Note that handleEvent() is ignored on event listeners that
aren't called.)
You can check whether any option is supported this way. Just add a getter for that
option using code similar to what is shown above.
Then, when you want to create an actual event listener that uses the options in
question, you can do something like this:
someElement.addEventListener(
"mouseup",
handleMouseUp,
passiveSupported ? { passive: true } : false
Here we're adding a listener for the mouseup
event on the element someElement. For the third parameter, if
passiveSupported is true, we're specifying an
options object with passive set to
true; otherwise, we know that we need to pass a Boolean, and we pass
false as the value of the useCapture parameter.
If you'd prefer, you can use a third-party library like Modernizr or Detect It to do this test for you.
You can learn more from the article about
EventListenerOptions
from the Web Incubator Community Group.
Examples
Examples
Add a simple listener
Add a simple listener
This example demonstrates how to use
addEventListener()
to watch for mouse
clicks on an element.
<table id="outside">
<td id="t1">one</td>
<td id="t2">two</td>
</table>
JavaScript
// Function to change the content of t2
function modifyText() {
const t2 = document.getElementById("t2");
const isNodeThree = t2.firstChild.nodeValue === "three";
t2.firstChild.nodeValue = isNodeThree ? "two" : "three";
// Add event listener to table
const el = document.getElementById("outside");
el.addEventListener("click", modifyText, false);
In this code, modifyText() is a listener for click events
registered using addEventListener(). A click anywhere in the table bubbles
up to the handler and runs modifyText().
Result