EventTarget: addEventListener() method

Note:This feature is available inWeb Workers.

TheaddEventListener()method of theEventTargetinterface sets 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 therecommendedway 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 anonXYZproperty, 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 type on theEventTargeton 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 anaddEventListenercall, the second function willalsobe added to the list of event listeners for that target.

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

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

If an event listener is added to anEventTargetfrom 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

js
addEventListener(type,listener)
addEventListener(type,listener,options)
addEventListener(type,listener,useCapture)

Parameters

type

A case-sensitive string representing theevent typeto listen for.

listener

The object that receives a notification (an object that implements the Eventinterface) when an event of the specified type occurs. This must benull,an object with ahandleEvent()method, or a JavaScript function.See The event listener callbackfor details on the callback itself.

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 registeredlistenerbefore being dispatched to any EventTargetbeneath it in the DOM tree. If not specified, defaults tofalse.

onceOptional

A boolean value indicating that thelistener should be invoked at most once after being added. Iftrue,the listenerwould be automatically removed when invoked. If not specified, defaults tofalse.

passiveOptional

A boolean value that, iftrue,indicates that the function specified bylistenerwill never callpreventDefault().If a passive listener does callpreventDefault(),the user agent will do nothing other than generate a console warning.

If this option is not specified it defaults tofalse– except that in browsers other than Safari, it defaults totrueforwheel,mousewheel,touchstartandtouchmoveevents. SeeUsing passive listenersto learn more.

signalOptional

AnAbortSignal.The listener will be removed when the givenAbortSignalobject'sabort()method is called. If not specified, noAbortSignalis associated with the listener.

useCaptureOptional

A boolean value indicating whether events of this type will be dispatched to the registeredlistenerbeforebeing dispatched to anyEventTargetbeneath 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. SeeDOM Level 3 EventsandJavaScript Event orderfor a detailed explanation. If not specified,useCapturedefaults 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 thecapturingphase are called before event listeners in any non-capturing phases.

wantsUntrustedOptional Non-standard

A Firefox (Gecko)-specific parameter. Iftrue,the listener receives synthetic events dispatched by web content (the default isfalsefor browserchromeandtruefor regular web pages). This parameter 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 or an object whosehandleEvent()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 onEventdescribing the event that has occurred, and it returns nothing.

For example, an event handler callback that can be used to handle both fullscreenchangeand fullscreenerrormight look like this:

js
functionhandleEvent(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 thepassiveoption:

js
letpassiveSupported=false;

try{
constoptions={
getpassive(){
// This function will be called when the browser
// attempts to access the passive property.
passiveSupported=true;
returnfalse;
},
};

window.addEventListener("test",null,options);
window.removeEventListener("test",null,options);
}catch(err){
passiveSupported=false;
}

This creates anoptionsobject with a getter function for the passiveproperty; the getter sets a flag, passiveSupported,totrueif it gets called. That means that if the browser checks the value of thepassiveproperty on the optionsobject,passiveSupportedwill be set totrue;otherwise, it will remainfalse.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 callremoveEventListener()to clean up after ourselves. (Note thathandleEvent()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:

js
someElement.addEventListener(
"mouseup",
handleMouseUp,
passiveSupported?{passive:true}:false,
);

Here we're adding a listener for themouseup event on the elementsomeElement.For the third parameter, if passiveSupportedistrue,we're specifying an optionsobject withpassiveset to true;otherwise, we know that we need to pass a Boolean, and we pass falseas the value of theuseCaptureparameter.

You can learn more in theImplementing feature detectiondocumentation and the explainer about EventListenerOptions from theWeb Incubator Community Group.

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 ofthisinside the handler will be a reference to the element. It will be the same as the value of thecurrentTargetproperty of the event argument that is passed to the handler.

js
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 ownthiscontext.

js
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 ofthisin a manner consistent with theaddEventListener();an occurrence ofthiswithin the code represents a reference to the element.

html
<tableid="my_table"onclick="console.log(this.id);">
<!-- `this` refers to the table; logs 'my_table' --></table>

Note that the value ofthisinside a function,called bythe code in the attribute value, behaves as perstandard rules.This is shown in the following example:

html
<script>
functionlogID(){
console.log(this.id);
}
</script>
<tableid="my_table"onclick="logID();">
<!-- when called, `this` will refer to the global object --></table>

The value ofthiswithinlogID()is a reference to the global objectWindow(orundefinedin the case ofstrict mode.

Specifying "this" using bind()

TheFunction.prototype.bind()method lets you establish a fixed thiscontext for all subsequent calls — bypassing problems where it's unclear whatthiswill be, depending on the context from which your function was called. Note, however, that you'll need to keep a reference to the listener around so you can remove it later.

This is an example with and withoutbind():

js
classSomething{
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
}
}

consts=newSomething(document.body);

Another solution is using a special function calledhandleEvent()to catch any events:

js
classSomething{
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;
}
}
}

consts=newSomething(document.body);

Another way of handling the reference tothisis to use an arrow function, which doesn't create a separatethiscontext.

js
classSomeClass{
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;
}
}
}

constmyObject=newSomeClass();
myObject.register();

Getting data into and out of an event listener

Event listeners only take one argument, anEventor 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 createclosuresinstead.

The functions passed as event listeners have access to all variables declared in the outer scopes that contain the function.

js
constmyButton=document.getElementById("my-button-id");
letsomeString="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 guidefor more information about function scopes.

Memory issues

js
constelts=document.getElementsByTagName("*");

// Case 1
for(consteltofelts){
elt.addEventListener(
"click",
(e)=>{
// Do something
},
false,
);
}

// Case 2
functionprocessEvent(e){
// Do something
}

for(consteltofelts){
elt.addEventListener("click",processEvent,false);
}

In the first case above, a new (anonymous) handler function is created with each iteration of the loop. In the second case, the same previously declared function is used as an event handler, which results in smaller memory consumption because there is only one handler function created. Moreover, in the first case, it is not possible to call removeEventListener()because no reference to the anonymous function is kept (or here, not kept to any of the multiple anonymous functions the loop might create.) In the second case, it's possible to do myElement.removeEventListener( "click", processEvent, false) becauseprocessEventis the function reference.

Actually, regarding memory consumption, the lack of keeping a function reference is not the real issue; rather it is the lack of keeping astaticfunction reference.

Using passive listeners

If an event has a default action — for example, awheelevent 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 thepassiveoption 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 thepassiveoption as always beingfalse.However, to realize the scroll performance benefits of passive listeners in legacy code, modern browsers have changed the default value of thepassiveoption totruefor thewheel,mousewheel,touchstartandtouchmoveevents 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 thepassiveoption isfalse,you must explicitly set the option tofalse(rather than relying on the default).

You don't need to worry about the value ofpassivefor the basicscrollevent. Since it can't be canceled, event listeners can't block page rendering anyway.

SeeImproving scroll performance using passive listenersfor an example showing the effect of passive listeners.

Older browsers

In older browsers that don't support theoptionsparameter to addEventListener(),attempting to use it prevents the use of the useCaptureargument without proper use offeature detection.

Examples

Add a simple listener

This example demonstrates how to useaddEventListener()to watch for mouse clicks on an element.

HTML

html
<tableid="outside">
<tr>
<tdid="t1">one</td>
</tr>
<tr>
<tdid="t2">two</td>
</tr>
</table>

JavaScript

js
// Function to change the content of t2
functionmodifyText(){
constt2=document.getElementById("t2");
constisNodeThree=t2.firstChild.nodeValue==="three";
t2.firstChild.nodeValue=isNodeThree?"two":"three";
}

// Add event listener to table
constel=document.getElementById("outside");
el.addEventListener("click",modifyText,false);

In this code,modifyText()is a listener forclickevents registered usingaddEventListener().A click anywhere in the table bubbles up to the handler and runsmodifyText().

Result

Add an abortable listener

This example demonstrates how to add anaddEventListener()that can be aborted with anAbortSignal.

HTML

html
<tableid="outside">
<tr>
<tdid="t1">one</td>
</tr>
<tr>
<tdid="t2">two</td>
</tr>
</table>

JavaScript

js
// Add an abortable event listener to table
constcontroller=newAbortController();
constel=document.getElementById("outside");
el.addEventListener("click",modifyText,{signal:controller.signal});

// Function to change the content of t2
functionmodifyText(){
constt2=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 theAbortControllerwe 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 the event listener.

HTML

html
<tableid="outside">
<tr>
<tdid="t1">one</td>
</tr>
<tr>
<tdid="t2">two</td>
</tr>
</table>

JavaScript

js
// Function to change the content of t2
functionmodifyText(new_text){
constt2=document.getElementById("t2");
t2.firstChild.nodeValue=new_text;
}

// Function to add event listener to table
constel=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 is responsible for actually responding to the event.

Result

Event listener with an arrow function

This example demonstrates a simple event listener implemented using arrow function notation.

HTML

html
<tableid="outside">
<tr>
<tdid="t1">one</td>
</tr>
<tr>
<tdid="t2">two</td>
</tr>
</table>

JavaScript

js
// Function to change the content of t2
functionmodifyText(new_text){
constt2=document.getElementById("t2");
t2.firstChild.nodeValue=new_text;
}

// Add event listener to table with an arrow function
constel=document.getElementById("outside");
el.addEventListener(
"click",
()=>{
modifyText("four");
},
false,
);

Result

Please note that while anonymous and arrow functions are similar, they have different thisbindings. While anonymous (and all traditional JavaScript functions) create their ownthisbindings, arrow functions inherit the thisbinding of the containing function.

That means that the variables and constants available to the containing function are also available to the event handler when using an arrow function.

Example of options usage

HTML

html
<divclass="outer">
outer, once & none-once
<divclass="middle"target="_blank">
middle, capture & none-capture
<aclass="inner1"href="https:// mozilla.org"target="_blank">
inner1, passive & preventDefault(which is not allowed)
</a>
<aclass="inner2"href="https://developer.mozilla.org/"target="_blank">
inner2, none-passive & preventDefault(not open new page)
</a>
</div>
</div>
<hr/>
<buttonclass="clear-button">Clear logs</button>
<sectionclass="demo-logs"></section>

CSS

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;
}

JavaScript

js
constouter=document.querySelector(".outer");
constmiddle=document.querySelector(".middle");
constinner1=document.querySelector(".inner1");
constinner2=document.querySelector(".inner2");

constcapture={
capture:true,
};
constnoneCapture={
capture:false,
};
constonce={
once:true,
};
constnoneOnce={
once:false,
};
constpassive={
passive:true,
};
constnonePassive={
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);

functiononceHandler(event){
log("outer, once");
}
functionnoneOnceHandler(event){
log("outer, none-once, default\n");
}
functioncaptureHandler(event){
//event.stopImmediatePropagation();
log("middle, capture");
}
functionnoneCaptureHandler(event){
log("middle, none-capture, default");
}
functionpassiveHandler(event){
// Unable to preventDefault inside passive event listener invocation.
event.preventDefault();
log("inner1, passive, open new page");
}
functionnonePassiveHandler(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.

Before using a particular value in theoptionsobject, it's a good idea to ensure that the user's browser supports it, since these are an addition that not all browsers have supported historically. SeeSafely detecting option supportfor details.

Event listener with multiple options

You can set more than one of the options in theoptionsparameter. 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

html
<buttonid="example-button">You have not clicked this button.</button>
<buttonid="reset-button">Click this button to reset the first button.</button>

JavaScript

js
constbuttonToBeClicked=document.getElementById("example-button");

constresetButton=document.getElementById("reset-button");

// the text that the button is initialized with
constinitialText=buttonToBeClicked.textContent;

// the text that the button contains after being clicked
constclickedText="You have clicked this button.";

// we hoist the event listener callback function
// to prevent having duplicate listeners attached
functioneventListener(){
buttonToBeClicked.textContent=clickedText;
}

functionaddListener(){
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 again
resetButton.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

html
<divid="container">
<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>
<inputtype="checkbox"id="passive"name="passive"checked/>
<labelfor="passive">passive</label>
</div>

JavaScript

The code adds a listener to the container'swheelevent, which by default scrolls the container. The listener runs a long-running operation. Initially the listener is added with thepassiveoption, and whenever the checkbox is toggled, the code toggles thepassiveoption.

js
constpassive=document.querySelector("#passive");
passive.addEventListener("change",(event)=>{
container.removeEventListener("wheel",wheelHandler);
container.addEventListener("wheel",wheelHandler,{
passive:passive.checked,
once:true,
});
});

constcontainer=document.querySelector("#container");
container.addEventListener("wheel",wheelHandler,{
passive:true,
once:true,
});

functionwheelHandler(){
functionisPrime(n){
for(letc=2;c<=Math.sqrt(n);++c){
if(n%c===0){
returnfalse;
}
}
returntrue;
}

constquota=1000000;
constprimes=[];
constmaximum=1000000;

while(primes.length<quota){
constcandidate=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 Standard
#ref-for-dom-eventtarget-addeventlistener③

Browser compatibility

BCD tables only load in the browser

See also