EventTarget: addEventListener() method
BaselineWidely available *
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
* Some parts of this feature may have varying levels of support.
Note: This feature is available inWeb Workers.
TheaddEventListener()
method of theEventTarget
interfacesets up a function that will be called whenever the specified event is delivered to the target.
Common targets areElement
, or its children,Document
, andWindow
,but the target may be any object that supports events (such asIDBRequest
).
Note:TheaddEventListener()
method is therecommended way to register an event listener. The benefits are as follows:
- It allows adding more than one handler for an event. This is particularlyuseful for libraries, JavaScript modules, or any other kind ofcode 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 methodaddEventListener()
works by adding a function, or an object that implements ahandleEvent()
function, to the list of event listeners for the specified event typeon theEventTarget
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 anaddEventListener
call, the second function willalso be added to the list of event listeners for that target.
Indeed, anonymous functions are not identical even if defined usingthesame unchanging source-code called repeatedly,even if in a loop.
Repeatedly defining the same unnamed function in such cases can beproblematic. (SeeMemory issues, below.)
If an event listener is added to anEventTarget
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
type
A case-sensitive string representing theevent type to listen for.
listener
The object that receives a notification (an object that implements the
Event
interface) when an event of the specified type occurs. This mustbenull
, an object with ahandleEvent()
method, or a JavaScriptfunction. SeeThe event listener callback for details on the callback itself.options
OptionalAn object that specifies characteristics about the event listener. The availableoptions are:
capture
OptionalA boolean value indicating that events of this type will be dispatchedto the registered
listener
before being dispatched to anyEventTarget
beneath it in the DOM tree. If not specified, defaults tofalse
.once
OptionalA boolean value indicating that the
listener
should be invoked at most once after being added. Iftrue
, thelistener
would be automatically removed when invoked. If not specified, defaults tofalse
.passive
OptionalA boolean value that, if
true
, indicates that the function specified bylistener
will never callpreventDefault()
. If a passive listener callspreventDefault()
, nothing will happen and a console warning may be generated.If this option is not specified it defaults to
false
– except that in browsers other than Safari, it defaults totrue
forwheel
,mousewheel
,touchstart
andtouchmove
events. SeeUsing passive listeners to learn more.signal
OptionalAn
AbortSignal
. The listener will be removed when theabort()
method of theAbortController
which owns theAbortSignal
is called. If not specified, noAbortSignal
is associated with the listener.
useCapture
OptionalA boolean value indicating whether events of this type will be dispatched tothe registered
listener
before being dispatched toanyEventTarget
beneath it in the DOM tree. Events that are bubblingupward through the tree will not trigger a listener designated to use capture. Eventbubbling and capturing are two ways of propagating events that occur in an elementthat is nested within another element, when both elements have registered a handle forthat event. The event propagation mode determines the order in which elements receivethe event. Seethe DOM spec andJavaScript Event order for a detailed explanation.If not specified,useCapture
defaults tofalse
.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 thecapturing phase are called before event listeners in the target and bubbling phases.
wantsUntrusted
OptionalNon-standardA Firefox (Gecko)-specific parameter. If
true
, the listener receivessynthetic events dispatched by web content (the default isfalse
forbrowserchrome andtrue
for regular web pages). Thisparameter is useful for code found in add-ons, as well as the browser itself.
Return value
None (undefined
).
Usage notes
The event listener callback
The event listener can be specified as either a callback function oran object whosehandleEvent()
method serves as the callback function.
The callback function itself has the same parameters and return value as thehandleEvent()
method; that is, the callback accepts a single parameter: anobject based onEvent
describing the event that has occurred, and itreturns nothing.
For example, an event handler callback that can be used to handle bothfullscreenchange
andfullscreenerror
might look like this:
function handleEvent(event) { if (event.type === "fullscreenchange") { /* handle a full screen toggle */ } else { /* handle a full screen toggle error */ }}
The value of "this" within the handler
It is often desirable to reference the element on which the event handler was fired,such as when using a generic handler for a set of similar elements.
When attaching a handler function to an element usingaddEventListener()
,the value ofthis
inside the handler will be a reference tothe element. It will be the same as the value of thecurrentTarget
property ofthe event argument that is passed to the handler.
my_element.addEventListener("click", function (e) { console.log(this.className); // logs the className of my_element console.log(e.currentTarget === this); // logs `true`});
As a reminder,arrow functions do not have their ownthis
context.
my_element.addEventListener("click", (e) => { console.log(this.className); // WARNING: `this` is not `my_element` console.log(e.currentTarget === this); // logs `false`});
If an event handler (for example,onclick
) is specified on an element in the HTML source, the JavaScript code in the attribute value is effectively wrapped in a handler function that binds the value ofthis
in a manner consistent with theaddEventListener()
; an occurrence ofthis
within the code represents a reference to the element.
<table> <!-- `this` refers to the table; logs 'my_table' --> …</table>
Note that the value ofthis
inside a function,called by the codein the attribute value, behaves as perstandard rules. This isshown in the following example:
<script> function logID() { console.log(this.id); }</script><table> <!-- when called, `this` will refer to the global object --> …</table>
The value ofthis
withinlogID()
is a reference to the globalobjectWindow
(orundefined
in the case ofstrict mode.
Specifying "this" using bind()
TheFunction.prototype.bind()
method lets you establish a fixedthis
context for all subsequent calls — bypassing problems where it's unclear whatthis
will be, depending onthe context from which your function was called. Note, however, that you'll need to keepa reference to the listener around so you can remove it later.
This is an example with and withoutbind()
:
class Something { name = "Something Good"; constructor(element) { // bind causes a fixed `this` context to be assigned to `onclick2` this.onclick2 = this.onclick2.bind(this); element.addEventListener("click", this.onclick1, false); element.addEventListener("click", this.onclick2, false); // Trick } onclick1(event) { console.log(this.name); // undefined, as `this` is the element } onclick2(event) { console.log(this.name); // 'Something Good', as `this` is bound to the Something instance }}const s = new Something(document.body);
Another solution is using a special function calledhandleEvent()
to catchany events:
class Something { name = "Something Good"; constructor(element) { // Note that the listeners in this case are `this`, not this.handleEvent element.addEventListener("click", this, false); element.addEventListener("dblclick", this, false); } handleEvent(event) { console.log(this.name); // 'Something Good', as this is bound to newly created object switch (event.type) { case "click": // some code here… break; case "dblclick": // some code here… break; } }}const s = new Something(document.body);
Another way of handling the reference tothis
is to use an arrow function, which doesn't create a separatethis
context.
class SomeClass { name = "Something Good"; register() { window.addEventListener("keydown", (e) => { this.someMethod(e); }); } someMethod(e) { console.log(this.name); switch (e.code) { case "ArrowUp": // some code here… break; case "ArrowDown": // some code here… break; } }}const myObject = new SomeClass();myObject.register();
Getting data into and out of an event listener
Event listeners only take one argument,anEvent
or a subclass ofEvent
,which is automatically passed to the listener, and the return value is ignored.Therefore, to get data into and out of an event listener, instead of passing the data through parameters and return values, you need to createclosures instead.
The functions passed as event listeners have access to all variables declared in the outer scopes that contain the function.
const myButton = document.getElementById("my-button-id");let someString = "Data";myButton.addEventListener("click", () => { console.log(someString); // 'Data' on first click, // 'Data Again' on second click someString = "Data Again";});console.log(someString); // Expected Value: 'Data' (will never output 'Data Again')
Readthe function guide for more information about function scopes.
Memory issues
const elems = document.getElementsByTagName("*");// Case 1for (const elem of elems) { elem.addEventListener( "click", (e) => { // Do something }, false, );}// Case 2function processEvent(e) { // Do something}for (const elem of elems) { elem.addEventListener("click", processEvent, false);}
In the first case above, a new (anonymous) handler function is created with eachiteration of the loop. In the second case, the same previously declared function is usedas an event handler, which results in smaller memory consumption because there is onlyone handler function created. Moreover, in the first case, it is not possible to callremoveEventListener()
because noreference to the anonymous function is kept (or here, not kept to any of the multipleanonymous functions the loop might create.) In the second case, it's possible to domyElement.removeEventListener("click", processEvent, false)
becauseprocessEvent
is the function reference.
Actually, regarding memory consumption, the lack of keeping a function reference is notthe real issue; rather it is the lack of keeping astatic function reference.
Using passive listeners
If an event has a default action — for example, awheel
event that scrolls the container by default — the browser is in general unable to start the default action until the event listener has finished, because it doesn't know in advance whether the event listener might cancel the default action by callingEvent.preventDefault()
. If the event listener takes too long to execute, this can cause a noticeable delay, also known asjank, before the default action can be executed.
By setting thepassive
option totrue
, an event listener declares that it will not cancel the default action, so the browser can start the default action immediately, without waiting for the listener to finish. If the listener does then callEvent.preventDefault()
, this will have no effect.
The specification foraddEventListener()
defines the default value for thepassive
option as always beingfalse
. However, to realize the scroll performance benefits of passive listeners in legacy code, modern browsers have changed the default value of thepassive
option totrue
for thewheel
,mousewheel
,touchstart
andtouchmove
events on the document-level nodesWindow
,Document
, andDocument.body
. That prevents the event listener fromcanceling the event, so it can't block page rendering while the user is scrolling.
Because of that, when you want to override that behavior and ensure thepassive
option isfalse
, you must explicitly set the option tofalse
(rather than relying on the default).
You don't need to worry about the value ofpassive
for the basicscroll
event.Since it can't be canceled, event listeners can't block page rendering anyway.
SeeImproving scroll performance using passive listeners for an example showing the effect of passive listeners.
Examples
Add a simple listener
This example demonstrates how to useaddEventListener()
to watch for mouseclicks on an element.
HTML
<table> <tr> <td>one</td> </tr> <tr> <td>two</td> </tr></table>
JavaScript
// Function to change the content of t2function modifyText() { const t2 = document.getElementById("t2"); const isNodeThree = t2.firstChild.nodeValue === "three"; t2.firstChild.nodeValue = isNodeThree ? "two" : "three";}// Add event listener to tableconst el = document.getElementById("outside");el.addEventListener("click", modifyText, false);
In this code,modifyText()
is a listener forclick
eventsregistered usingaddEventListener()
. A click anywhere in the table bubblesup to the handler and runsmodifyText()
.
Result
Add an abortable listener
This example demonstrates how to add anaddEventListener()
that can be aborted with anAbortSignal
.
HTML
<table> <tr> <td>one</td> </tr> <tr> <td>two</td> </tr></table>
JavaScript
// Add an abortable event listener to tableconst controller = new AbortController();const el = document.getElementById("outside");el.addEventListener("click", modifyText, { signal: controller.signal });// Function to change the content of t2function modifyText() { const t2 = document.getElementById("t2"); if (t2.firstChild.nodeValue === "three") { t2.firstChild.nodeValue = "two"; } else { t2.firstChild.nodeValue = "three"; controller.abort(); // remove listener after value reaches "three" }}
In the example above, we modify the code in the previous example such that after the second row's content changes to "three", we callabort()
from theAbortController
we passed to theaddEventListener()
call. That results in the value remaining as "three" forever because we no longer have any code listening for a click event.
Result
Event listener with anonymous function
Here, we'll take a look at how to use an anonymous function to pass parameters into theevent listener.
HTML
<table> <tr> <td>one</td> </tr> <tr> <td>two</td> </tr></table>
JavaScript
// Function to change the content of t2function modifyText(newText) { const t2 = document.getElementById("t2"); t2.firstChild.nodeValue = newText;}// Function to add event listener to tableconst el = document.getElementById("outside");el.addEventListener( "click", function () { modifyText("four"); }, false,);
Notice that the listener is an anonymous function that encapsulates code that is then,in turn, able to send parameters to themodifyText()
function, which isresponsible for actually responding to the event.
Result
Event listener with an arrow function
This example demonstrates an event listener implemented using arrow functionnotation.
HTML
<table> <tr> <td>one</td> </tr> <tr> <td>two</td> </tr></table>
JavaScript
// Function to change the content of t2function modifyText(newText) { const t2 = document.getElementById("t2"); t2.firstChild.nodeValue = newText;}// Add event listener to table with an arrow functionconst el = document.getElementById("outside");el.addEventListener( "click", () => { modifyText("four"); }, false,);
Result
Please note that while anonymous and arrow functions are similar, they have differentthis
bindings. While anonymous (and all traditional JavaScript functions)create their ownthis
bindings, arrow functions inherit thethis
binding of the containing function.
That means that the variables and constants available to the containing function arealso available to the event handler when using an arrow function.
Example of options usage
HTML
<div> outer, once & none-once <div> middle, capture & none-capture <a href="https://www.mozilla.org"> inner1, passive & preventDefault(which is not allowed) </a> <a href="https://developer.mozilla.org/"> inner2, none-passive & preventDefault(not open new page) </a> </div></div><hr /><button>Clear logs</button><section></section>
CSS
.outer,.middle,.inner1,.inner2 { display: block; width: 520px; padding: 15px; margin: 15px; text-decoration: none;}.outer { border: 1px solid red; color: red;}.middle { border: 1px solid green; color: green; width: 460px;}.inner1,.inner2 { border: 1px solid purple; color: purple; width: 400px;}
.demo-logs { width: 530px; height: 16rem; background-color: #ddd; overflow-x: auto; padding: 1rem;}
JavaScript
const clearBtn = document.querySelector(".clear-button");const demoLogs = document.querySelector(".demo-logs");function log(msg) { demoLogs.innerText += `${msg}\n`;}clearBtn.addEventListener("click", () => { demoLogs.innerText = "";});
const outer = document.querySelector(".outer");const middle = document.querySelector(".middle");const inner1 = document.querySelector(".inner1");const inner2 = document.querySelector(".inner2");const capture = { capture: true,};const noneCapture = { capture: false,};const once = { once: true,};const noneOnce = { once: false,};const passive = { passive: true,};const nonePassive = { passive: false,};outer.addEventListener("click", onceHandler, once);outer.addEventListener("click", noneOnceHandler, noneOnce);middle.addEventListener("click", captureHandler, capture);middle.addEventListener("click", noneCaptureHandler, noneCapture);inner1.addEventListener("click", passiveHandler, passive);inner2.addEventListener("click", nonePassiveHandler, nonePassive);function onceHandler(event) { log("outer, once");}function noneOnceHandler(event) { log("outer, none-once, default\n");}function captureHandler(event) { // event.stopImmediatePropagation(); log("middle, capture");}function noneCaptureHandler(event) { log("middle, none-capture, default");}function passiveHandler(event) { // Unable to preventDefault inside passive event listener invocation. event.preventDefault(); log("inner1, passive, open new page");}function nonePassiveHandler(event) { event.preventDefault(); // event.stopPropagation(); log("inner2, none-passive, default, not open new page");}
Result
Click the outer, middle, inner containers respectively to see how the options work.
Event listener with multiple options
You can set more than one of the options in theoptions
parameter. In the following example we are setting two options:
passive
, to assert that the handler will not callpreventDefault()
once
, to ensure that the event handler will only be called once.
HTML
<button>You have not clicked this button.</button><button>Click this button to reset the first button.</button>
JavaScript
const buttonToBeClicked = document.getElementById("example-button");const resetButton = document.getElementById("reset-button");// the text that the button is initialized withconst initialText = buttonToBeClicked.textContent;// the text that the button contains after being clickedconst clickedText = "You have clicked this button.";// we hoist the event listener callback function// to prevent having duplicate listeners attachedfunction eventListener() { buttonToBeClicked.textContent = clickedText;}function addListener() { buttonToBeClicked.addEventListener("click", eventListener, { passive: true, once: true, });}// when the reset button is clicked, the example button is reset,// and allowed to have its state updated againresetButton.addEventListener("click", () => { buttonToBeClicked.textContent = initialText; addListener();});addListener();
Result
Improving scroll performance using passive listeners
The following example shows the effect of settingpassive
. It includes a<div>
that contains some text, and a check box.
HTML
<div> <p> But down there it would be dark now, and not the lovely lighted aquarium she imagined it to be during the daylight hours, eddying with schools of tiny, delicate animals floating and dancing slowly to their own serene currents and creating the look of a living painting. That was wrong, in any case. The ocean was different from an aquarium, which was an artificial environment. The ocean was a world. And a world is not art. Dorothy thought about the living things that moved in that world: large, ruthless and hungry. Like us up here. </p></div><div> <input type="checkbox" name="passive" checked /> <label for="passive">passive</label></div>
#container { width: 150px; height: 200px; overflow: scroll; margin: 2rem 0; padding: 0.4rem; border: 1px solid black;}
JavaScript
The code adds a listener to the container'swheel
event, which by default scrolls the container. The listener runs a long-running operation. Initially the listener is added with thepassive
option, and whenever the checkbox is toggled, the code toggles thepassive
option.
const passive = document.querySelector("#passive");passive.addEventListener("change", (event) => { container.removeEventListener("wheel", wheelHandler); container.addEventListener("wheel", wheelHandler, { passive: passive.checked, once: true, });});const container = document.querySelector("#container");container.addEventListener("wheel", wheelHandler, { passive: true, once: true,});function wheelHandler() { function isPrime(n) { for (let c = 2; c <= Math.sqrt(n); ++c) { if (n % c === 0) { return false; } } return true; } const quota = 1000000; const primes = []; const maximum = 1000000; while (primes.length < quota) { const candidate = Math.floor(Math.random() * (maximum + 1)); if (isPrime(candidate)) { primes.push(candidate); } } console.log(primes);}
Result
The effect is that:
- Initially, the listener is passive, so trying to scroll the container with the wheel is immediate.
- If you uncheck "passive" and try to scroll the container using the wheel, then there is a noticeable delay before the container scrolls, because the browser has to wait for the long-running listener to finish.
Specifications
Specification |
---|
DOM # ref-for-dom-eventtarget-addeventlistener③ |