Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1111533 of EventTarget.addEventListener()

  • Revision slug: Web/API/EventTarget/addEventListener
  • Revision title: EventTarget.addEventListener()
  • Revision id: 1111533
  • Created:
  • Creator: paul.irish
  • Is current revision? Yes
  • Comment

Revision Content

{{apiref("DOM Events")}}

The EventTarget.addEventListener() method registers the specified listener on the {{domxref("EventTarget")}} it's called on. The event target may be an {{domxref("Element")}} in a document, the {{domxref("Document")}} itself, a {{domxref("Window")}}, or any other object that supports events (such as XMLHttpRequest).

Syntax

target.addEventListener(type, listener[, options]);
target.addEventListener(type, listener[, useCapture]);
target.addEventListener(type, listener[, useCapture, wantsUntrusted {{Non-standard_inline}}]); // Gecko/Mozilla only

Parameters

type
A string representing the event type to listen for.
listener
The object that receives a notification (an object that implements the {{domxref("Event")}} interface) when an event of the specified type occurs. This must be an object implementing the {{domxref("EventListener")}} interface, or simply a JavaScript function.
options {{optional_inline}}
An options object that specifies characteristics about the event listener. The available options are:
  • capture: A {{jsxref("Boolean")}} that indicates that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.  
  • once: A {{jsxref("Boolean")}} indicating that the listener should be invoked at most once after being added. If it is true, the listener would be removed automatically when it is invoked.
  • passive: A {{jsxref("Boolean")}} indicating that the listener will never call preventDefault(). If it does, the user agent should ignore it and generate a console warning.
  • {{non-standard_inline}} mozSystemGroup: Available only in code running in XBL or in Firefox' chrome, it is a {{jsxref("Boolean")}} defining if the listener is added to the system group.
useCapture {{optional_inline}}
A {{jsxref("Boolean")}} that indicates that events of this type will be dispatched to the registered 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 capturing and bubbling phases. Events in the target phase will trigger all listeners on an element regardless of the useCapture parameter.
Note: useCapture became optional only in more recent versions of the major browsers; for example, it was not optional before Firefox 6. You should provide this parameter for broadest compatibility.
wantsUntrusted {{Non-standard_inline}}
If true, the listener receives synthetic events dispatched by web content (the default is false for chrome and true for regular web pages). This parameter is only available in Gecko and is mainly useful for the code in add-ons and the browser itself. See Interaction between privileged and non-privileged pages for an example.

Example

Add a simple listener

HTML Content

<table id="outside">
    <tr><td id="t1">one</td></tr>
    <tr><td id="t2">two</td></tr>
</table>

JavaScript Content

// Function to change the content of t2
function modifyText() {
  var t2 = document.getElementById("t2");
  if (t2.firstChild.nodeValue == "three") {
    t2.firstChild.nodeValue = "two";
  } else {
    t2.firstChild.nodeValue = "three";
  }
}

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

{{EmbedLiveSample('Add_a_simple_listener')}}

In the above example, modifyText() is a listener for click events registered using addEventListener(). A click anywhere in the table bubbles up to the handler and run modifyText().

If you want to pass parameters to the listener function, you may use an anonymous function.

Event Listener with anonymous function

HTML Content

<table id="outside">
    <tr><td id="t1">one</td></tr>
    <tr><td id="t2">two</td></tr>
</table>

JavaScript Content

// Function to change the content of t2
function modifyText(new_text) {
  var t2 = document.getElementById("t2");
  t2.firstChild.nodeValue = new_text;    
}
 
// Function to add event listener to table
var el = document.getElementById("outside");
el.addEventListener("click", function(){modifyText("four")}, false);

{{EmbedLiveSample('Event_Listener_with_anonymous_function')}}

Notes

Why use addEventListener?

addEventListener is the way to register an event listener as specified in W3C DOM. Its benefits are as follows:

  • It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla extensions that need to work well with other libraries/extensions.
  • It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)
  • It works on any DOM element, not just HTML elements.

The alternative, older way to register event listeners, is described below.

Adding a listener during event dispatch

If an EventListener is added to an EventTarget while it is processing an event, that event does not trigger the listener. However, that same listener may be triggered during a later stage of event flow, such as the bubbling phase.

Multiple identical event listeners

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the removeEventListener method.

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 using addEventListener(), the value of this inside the handler is a reference to the element. It is the same as the value of the currentTarget property of the event argument that is passed to the handler.

If an event attribute (e.g., 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 of this in a manner consistent with the use of addEventListener(); an occurrence of this within the code represents a reference to the element. Note that the value of this inside a function called by the code in the attribute value behaves as per standard rules. Therefore, given the following example:

<table id="t" onclick="modifyText();">
  . . .

The value of this within modifyText() when called via the onclick event is a reference to the global (window) object (or undefined in the case of strict mode)

Note: JavaScript 1.8.5 introduces the Function.prototype.bind() method, which lets you specify the value that should be used as this for all calls to a given function. This method lets you easily bypass problems where it's unclear what this will 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 later remove it.

This is an example with and without bind:

var Something = function(element) {
  // |this| is a newly created object
  this.name = 'Something Good';
  this.onclick1 = function(event) {
    console.log(this.name); // undefined, as |this| is the element
  };
  this.onclick2 = function(event) {
    console.log(this.name); // 'Something Good', as |this| is bound to newly created object
  };
  element.addEventListener('click', this.onclick1, false);
  element.addEventListener('click', this.onclick2.bind(this), false); // Trick
}
var s = new Something(document.body);

A problem in the example above is that you cannot remove the listener with bind. Another solution is using a special function called handleEvent to catch any events:

var Something = function(element) {
  // |this| is a newly created object
  this.name = 'Something Good';
  this.handleEvent = function(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;
    }
  };

  // Note that the listeners in this case are |this|, not this.handleEvent
  element.addEventListener('click', this, false);
  element.addEventListener('dblclick', this, false);

  // You can properly remove the listeners
  element.removeEventListener('click', this, false);
  element.removeEventListener('dblclick', this, false);
}
var s = new Something(document.body);

Legacy Internet Explorer and attachEvent

In Internet Explorer versions before IE 9, you have to use attachEvent rather than the standard addEventListener. For IE, modify the preceding example to:

if (el.addEventListener) {
  el.addEventListener('click', modifyText, false); 
} else if (el.attachEvent)  {
  el.attachEvent('onclick', modifyText);
}

There is a drawback to attachEvent, the value of this will be a reference to the window object instead of the element on which it was fired.

Compatibility

You can work around the addEventListener, removeEventListener, Event.preventDefault and Event.stopPropagation not being supported by IE 8 using the following code at the beginning of your script. The code supports the use of handleEvent and also the DOMContentLoaded event.

Note: useCapture is not supported, as IE 8 does not have any alternative method of it. Please also note that the following code only adds support to IE 8.

Also note that this IE8 polyfill ONLY works in standards mode: a doctype declaration is required.

(function() {
  if (!Event.prototype.preventDefault) {
    Event.prototype.preventDefault=function() {
      this.returnValue=false;
    };
  }
  if (!Event.prototype.stopPropagation) {
    Event.prototype.stopPropagation=function() {
      this.cancelBubble=true;
    };
  }
  if (!Element.prototype.addEventListener) {
    var eventListeners=[];
    
    var addEventListener=function(type,listener /*, useCapture (will be ignored) */) {
      var self=this;
      var wrapper=function(e) {
        e.target=e.srcElement;
        e.currentTarget=self;
        if (typeof listener.handleEvent != 'undefined') {
          listener.handleEvent(e);
        } else {
          listener.call(self,e);
        }
      };
      if (type=="DOMContentLoaded") {
        var wrapper2=function(e) {
          if (document.readyState=="complete") {
            wrapper(e);
          }
        };
        document.attachEvent("onreadystatechange",wrapper2);
        eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper2});
        
        if (document.readyState=="complete") {
          var e=new Event();
          e.srcElement=window;
          wrapper2(e);
        }
      } else {
        this.attachEvent("on"+type,wrapper);
        eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper});
      }
    };
    var removeEventListener=function(type,listener /*, useCapture (will be ignored) */) {
      var counter=0;
      while (counter<eventListeners.length) {
        var eventListener=eventListeners[counter];
        if (eventListener.object==this && eventListener.type==type && eventListener.listener==listener) {
          if (type=="DOMContentLoaded") {
            this.detachEvent("onreadystatechange",eventListener.wrapper);
          } else {
            this.detachEvent("on"+type,eventListener.wrapper);
          }
          eventListeners.splice(counter, 1);
          break;
        }
        ++counter;
      }
    };
    Element.prototype.addEventListener=addEventListener;
    Element.prototype.removeEventListener=removeEventListener;
    if (HTMLDocument) {
      HTMLDocument.prototype.addEventListener=addEventListener;
      HTMLDocument.prototype.removeEventListener=removeEventListener;
    }
    if (Window) {
      Window.prototype.addEventListener=addEventListener;
      Window.prototype.removeEventListener=removeEventListener;
    }
  }
})();

Older way to register event listeners

addEventListener() was introduced with the DOM 2 Events specification. Before then, event listeners were registered as follows:

// Pass a function reference — do not add '()' after it, which would call the function!
el.onclick = modifyText;

// Using a function expression
element.onclick = function() {
  // ... function logic ...
};

This method replaces the existing click event listener(s) on the element if there are any. Similarly for other events and associated event handlers such as blur (onblur), keypress (onkeypress), and so on.

Because it was essentially part of DOM 0, this method is very widely supported and requires no special cross–browser code; hence it is normally used to register event listeners dynamically unless the extra features of addEventListener() are needed.

Memory issues

var i;
var els = document.getElementsByTagName('*');

// Case 1
for(i=0 ; i<els.length ; i++){
  els[i].addEventListener("click", function(e){/*do something*/}, false);
}

// Case 2
function processEvent(e){
  /*do something*/
}

for(i=0 ; i<els.length ; i++){
  els[i].addEventListener("click", processEvent, false);
}

In the first case, a new (anonymous) function is created at each loop turn. In the second case, the same previously declared function is used as an event handler. This results in smaller memory consumption. Moreover, in the first case, since no reference to the anonymous functions is kept, it is not possible to call element.removeEventListener because we do not have a reference to the handler, while, in the second case, it's possible to do myElement.removeEventListener("click", processEvent, false).

Improving scrolling performance with passive listeners

var elem = document.getElementById('elem');
elem.addEventListener('touchmove', function listener() {
  /* do something */
}, { passive: true });

This way a touchmove listener will not block while a user is scrolling (same applies to wheel events). Demo available here (Google Developers Page).

Beware: Browsers who do not support event listener options will see the 3rd argument as useCapture and therefore as true.

 

Specifications

Specification Status Comment
{{SpecName("DOM WHATWG", "#dom-eventtarget-addeventlistener", "EventTarget.addEventListener()")}} {{Spec2("DOM WHATWG")}}  
{{SpecName("DOM4", "#dom-eventtarget-addeventlistener", "EventTarget.addEventListener()")}} {{Spec2("DOM4")}}  
{{SpecName("DOM2 Events", "#Events-EventTarget-addEventListener", "EventTarget.addEventListener()")}} {{Spec2("DOM2 Events")}} Initial definition

Browser compatibility

{{CompatibilityTable}}
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 1.0[1][2] {{CompatGeckoDesktop(1.0)}}[3] 9.0[4] 7 1.0[1]
useCapture made optional 1.0 {{CompatGeckoDesktop(6)}} 9.0 11.60 {{CompatVersionUnknown}}
options parameter (with capture and passive values)[5]

{{CompatChrome(49.0)}} (capture) {{CompatChrome(51.0)}} (passive)

{{CompatGeckoDesktop(49)}} {{CompatNo}} {{CompatNo}} Landed in Nightly {{webkitbug(158601)}}
once value in the options parameter {{CompatChrome(55)}} {{CompatGeckoDesktop(50)}} {{CompatNo}} {{CompatNo}} Landed in Nightly {{webkitbug(149466)}}
Feature Android Android Webview Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support 1.0

{{CompatVersionUnknown}}[2]

{{CompatGeckoMobile(1.0)}}[3] 9.0 6.0 1.0[1]

{{CompatVersionUnknown}}[2]

useCapture made optional {{CompatUnknown}}

{{CompatVersionUnknown}}

{{CompatGeckoMobile(6)}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}}

{{CompatVersionUnknown}}

options parameter (with capture and passive values)[5] {{CompatNo}} {{CompatChrome(49.0)}} (capture) {{CompatChrome(51.0)}} (passive) {{CompatGeckoMobile(49)}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}} {{CompatChrome(49.0)}} (capture) {{CompatChrome(51.0)}} (passive)
once value in the options parameter {{CompatNo}} {{CompatNo}} {{CompatGeckoDesktop(50)}} {{CompatNo}} {{CompatNo}}

[1] Although WebKit has explicitly added [optional] to the useCapture parameter as recently as June 2011, it had been working before the change. The new change landed in Safari 5.1 and Chrome 13.

[2] Before Chrome 49, the type and listener parameters were optional.

[3] Prior to Firefox 6, the browser would throw an error if the useCapture parameter was not explicitly false. Prior to Gecko 9.0 {{geckoRelease("9.0")}}, addEventListener() would throw an exception if the listener parameter was null; now the method returns without error, but without doing anything.

[4] Older versions of Internet Explorer support the proprietary {{domxref("EventTarget.attachEvent")}} method instead.

[5] For backwards compatibility, browsers that support options allow the third parameter to be either options or {{jsxref("Boolean")}}.

See also

Revision Source

<div>{{apiref("DOM Events")}}</div>

<p>The <code><strong>EventTarget.addEventListener()</strong></code> method registers the specified listener on the {{domxref("EventTarget")}} it's called on. The event target may be an {{domxref("Element")}} in a document, the {{domxref("Document")}} itself, a {{domxref("Window")}}, or any other object that supports events (such as <code><a href="/en-US/docs/DOM/XMLHttpRequest">XMLHttpRequest</a></code>).</p>

<h2 id="Syntax">Syntax</h2>

<pre class="syntaxbox">
<code><em>target</em>.addEventListener(<em>type</em>, <em>listener[</em>, <em>options</em>]);
<em>target</em>.addEventListener(<em>type</em>, <em>listener[</em>, <em>useCapture</em>]);
<em>target</em>.addEventListener(<em>type</em>, <em>listener[</em>, <em>useCapture</em>, <em>wantsUntrusted </em>{{Non-standard_inline}}]); // Gecko/Mozilla only</code>
</pre>

<h3 id="Parameters">Parameters</h3>

<dl>
 <dt>type</dt>
 <dd>A string representing the <a href="/en-US/docs/Web/Events">event type</a> to listen for.</dd>
 <dt>listener</dt>
 <dd>The object that receives a notification (an object that implements the {{domxref("Event")}}&nbsp;interface) when an event of the specified type occurs. This must be an object implementing the {{domxref("EventListener")}} interface, or simply a JavaScript <a href="/en-US/docs/JavaScript/Guide/Functions">function</a>.</dd>
 <dt>options {{optional_inline}}</dt>
 <dd>An options object that specifies characteristics about the event listener. The available options are:
 <ul>
  <li><code>capture</code>: A&nbsp;{{jsxref("Boolean")}} that indicates that events of this type will be dispatched to the registered <code>listener</code>&nbsp;before being dispatched to any <code>EventTarget</code> beneath it in the DOM tree.&nbsp;&nbsp;</li>
  <li><code>once</code>: A {{jsxref("Boolean")}} indicating that the <code>listener</code> should be invoked at most once after being added. If it is <code>true</code>, the <code>listener</code> would be removed automatically when it is invoked.</li>
  <li><code>passive</code>: A {{jsxref("Boolean")}} indicating that the <code>listener</code> will never call <code>preventDefault()</code>. If it does, the user agent should ignore it and generate a console warning.</li>
  <li>{{non-standard_inline}}<code> mozSystemGroup</code>: Available only in code running in XBL or in Firefox' chrome, it is a {{jsxref("Boolean")}} defining if the listener is added to the system group.</li>
 </ul>
 </dd>
 <dt>useCapture {{optional_inline}}</dt>
 <dd>A&nbsp;{{jsxref("Boolean")}} that indicates that events of this type will be dispatched to the registered <code>listener</code>&nbsp;before being dispatched to any <code>EventTarget</code> beneath it in the DOM tree.&nbsp;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&nbsp;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.&nbsp;See <a href="https://www.w3.org/TR/DOM-Level-3-Events/#event-flow">DOM Level 3 Events</a>&nbsp;and <a href="https://www.quirksmode.org/js/events_order.html#link4">JavaScript Event order</a>&nbsp;for a detailed explanation. If not specified, <code>useCapture</code> defaults to <code>false</code>.
 <div class="note"><strong>Note:</strong> For event listeners attached to the event target; the event is in the target phase, rather than capturing and bubbling phases. Events in the target phase will trigger all listeners on an element regardless of the <code>useCapture</code> parameter.</div>

 <div class="note"><strong>Note:</strong> <code>useCapture</code> became optional only in more recent versions of the major browsers; for example, it was not optional before Firefox 6. You should provide this parameter for broadest compatibility.</div>
 </dd>
 <dt>wantsUntrusted {{Non-standard_inline}}</dt>
 <dd>If <code>true</code>, the listener receives synthetic events dispatched by web content (the default is <code>false</code> for chrome and <code>true</code> for regular web pages). This parameter is only available in Gecko and is mainly useful for the code in add-ons and the browser itself. See <a href="/en-US/docs/Code_snippets/Interaction_between_privileged_and_non-privileged_pages">Interaction between privileged and non-privileged pages</a> for an example.</dd>
</dl>

<h2 id="Example">Example</h2>

<h3 id="Add_a_simple_listener">Add a simple listener</h3>

<h4 id="HTML_Content">HTML Content</h4>

<pre class="brush: html">
&lt;table id="outside"&gt;
    &lt;tr&gt;&lt;td id="t1"&gt;one&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td id="t2"&gt;two&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;
</pre>

<h4 id="JavaScript_Content">JavaScript Content</h4>

<pre class="brush: js">
// Function to change the content of t2
function modifyText() {
  var t2 = document.getElementById("t2");
  if (t2.firstChild.nodeValue == "three") {
    t2.firstChild.nodeValue = "two";
  } else {
    t2.firstChild.nodeValue = "three";
  }
}

// add event listener to table
var el = document.getElementById("outside");
el.addEventListener("click", modifyText, false);
</pre>

<p>{{EmbedLiveSample('Add_a_simple_listener')}}</p>

<p>In the above example, <code>modifyText()</code> is a listener for <code>click</code> events registered using <code>addEventListener()</code>. A click anywhere in the table bubbles up to the handler and run <code>modifyText()</code>.</p>

<p>If you want to pass parameters to the listener function, you may use an anonymous function.</p>

<h3 id="Event_Listener_with_anonymous_function">Event Listener with anonymous function</h3>

<h4 id="HTML_Content_2">HTML Content</h4>

<pre class="brush: html">
&lt;table id="outside"&gt;
    &lt;tr&gt;&lt;td id="t1"&gt;one&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td id="t2"&gt;two&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;</pre>

<h4 id="JavaScript_Content_2">JavaScript Content</h4>

<pre class="brush: js">
// Function to change the content of t2
function modifyText(new_text) {
  var t2 = document.getElementById("t2");
  t2.firstChild.nodeValue = new_text;    
}
 
// Function to add event listener to table
var el = document.getElementById("outside");
el.addEventListener("click", function(){modifyText("four")}, false);
</pre>

<p>{{EmbedLiveSample('Event_Listener_with_anonymous_function')}}</p>

<h2 id="Notes">Notes</h2>

<h3 id="Why_use_addEventListener">Why use <code>addEventListener</code>?</h3>

<p><code>addEventListener</code> is the way to register an event listener as specified in W3C DOM. Its benefits are as follows:</p>

<ul>
 <li>It allows adding more than a single handler for an event. This is particularly useful for <a href="/en-US/docs/DHTML">DHTML</a> libraries or <a href="/en-US/docs/Extensions">Mozilla extensions</a> that need to work well with other libraries/extensions.</li>
 <li>It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)</li>
 <li>It works on any DOM element, not just HTML elements.</li>
</ul>

<p>The alternative, <a href="#Older_way_to_register_event_listeners">older way to register event listeners</a>, is described below.</p>

<h3 id="Adding_a_listener_during_event_dispatch">Adding a listener during event dispatch</h3>

<p>If an <code>EventListener</code> is added to an <code>EventTarget</code> while it is processing an event, that event does not trigger&nbsp;the listener. However, that same listener may be triggered during a later stage of event flow, such as the bubbling phase.</p>

<h3 id="Multiple_identical_event_listeners">Multiple identical event listeners</h3>

<p>If multiple identical <code>EventListener</code>s are registered on the same <code>EventTarget</code> with the same parameters, the duplicate instances are discarded. They do not cause the <code>EventListener</code> to be called twice, and they do not need to be removed manually with the <a href="/en-US/docs/DOM/EventTarget.removeEventListener">removeEventListener</a> method.</p>

<h3 id="The_value_of_this_within_the_handler">The value of <code>this</code> within the handler</h3>

<p>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.</p>

<p>When attaching a handler function to an element using <code>addEventListener()</code>, the value of <code>this</code>&nbsp;inside the handler is a reference to the element. It is the same as the value of the&nbsp;<code>currentTarget</code> property of the event argument that is passed to the handler.</p>

<p>If an event attribute (e.g., <code>onclick</code>) is&nbsp;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 of <code>this</code>&nbsp;in a manner consistent with the use of <code>addEventListener()</code>; an occurrence of&nbsp;<code>this</code> within the&nbsp;code represents a reference to the element. Note that the value of <code>this</code> inside a function <em>called by&nbsp;</em>the code in the attribute value&nbsp;behaves as per <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">standard rules</a>. Therefore, given the following example:</p>

<pre class="brush: html">
&lt;table id="t" onclick="modifyText();"&gt;
  . . .
</pre>

<p>The value of <code>this</code> within <code>modifyText()</code> when called via the <code>onclick</code> event is a reference to the global (<code>window</code>) object (or <code>undefined</code> in the case of <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>)</p>

<div class="note"><strong>Note:</strong> JavaScript 1.8.5 introduces the <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind">Function.prototype.bind()</a></code>&nbsp;method, which lets you specify the value that should be used as <code>this</code> for all calls to a given function. This method lets you easily bypass problems where it's unclear what this will 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 later remove it.</div>

<p>This is an example with and without <code>bind</code>:</p>

<pre class="brush: js">
var Something = function(element) {
  // |this| is a newly created object
  this.name = 'Something Good';
  this.onclick1 = function(event) {
    console.log(this.name); // undefined, as |this| is the element
  };
  this.onclick2 = function(event) {
    console.log(this.name); // 'Something Good', as |this| is bound to newly created object
  };
  element.addEventListener('click', this.onclick1, false);
  element.addEventListener('click', this.onclick2.bind(this), false); // Trick
}
var s = new Something(document.body);
</pre>

<p>A problem in the example above is that you cannot remove the listener with <code>bind</code>. Another solution is using a special function called <code>handleEvent</code> to catch any events:</p>

<pre class="brush: js">
var Something = function(element) {
  // |this| is a newly created object
  this.name = 'Something Good';
  this.handleEvent = function(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;
    }
  };

  // Note that the listeners in this case are |this|, not this.handleEvent
  element.addEventListener('click', this, false);
  element.addEventListener('dblclick', this, false);

  // You can properly remove the listeners
  element.removeEventListener('click', this, false);
  element.removeEventListener('dblclick', this, false);
}
var s = new Something(document.body);
</pre>

<h3 id="Legacy_Internet_Explorer_and_attachEvent">Legacy Internet Explorer and attachEvent</h3>

<p>In Internet Explorer versions before IE 9, you have to use <code><a href="https://msdn.microsoft.com/en-us/library/ms536343(VS.85).aspx">attachEvent</a></code> rather than the standard <code>addEventListener</code>. For IE, modify the preceding example to:</p>

<pre class="brush: js">
if (el.addEventListener) {
  el.addEventListener('click', modifyText, false); 
} else if (el.attachEvent)  {
  el.attachEvent('onclick', modifyText);
}
</pre>

<p>There is a drawback to <code>attachEvent</code>, the value of <code>this</code> will be a reference to the <code>window</code> object instead of the element on which it was fired.</p>

<h3 id="Compatibility">Compatibility</h3>

<p>You can work around the <code>addEventListener</code>, <code>removeEventListener</code>, <code>Event.preventDefault</code> and <code>Event.stopPropagation</code> not being supported by IE 8 using the following code at the beginning of your script. The code supports the use of <code>handleEvent</code> and also the <code>DOMContentLoaded</code> event.</p>

<div class="note">
<p><strong>Note: </strong>useCapture is not supported, as IE 8 does not have any alternative method of it. Please also note that the following code only adds support to IE 8.</p>

<p>Also note that this IE8&nbsp;polyfill ONLY works in standards mode: a doctype declaration is required.</p>
</div>

<pre class="brush: js">
(function() {
  if (!Event.prototype.preventDefault) {
    Event.prototype.preventDefault=function() {
      this.returnValue=false;
    };
  }
  if (!Event.prototype.stopPropagation) {
    Event.prototype.stopPropagation=function() {
      this.cancelBubble=true;
    };
  }
  if (!Element.prototype.addEventListener) {
    var eventListeners=[];
    
    var addEventListener=function(type,listener /*, useCapture (will be ignored) */) {
      var self=this;
      var wrapper=function(e) {
        e.target=e.srcElement;
        e.currentTarget=self;
        if (typeof listener.handleEvent != 'undefined') {
          listener.handleEvent(e);
        } else {
          listener.call(self,e);
        }
      };
      if (type=="DOMContentLoaded") {
        var wrapper2=function(e) {
          if (document.readyState=="complete") {
            wrapper(e);
          }
        };
        document.attachEvent("onreadystatechange",wrapper2);
        eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper2});
        
        if (document.readyState=="complete") {
          var e=new Event();
          e.srcElement=window;
          wrapper2(e);
        }
      } else {
        this.attachEvent("on"+type,wrapper);
        eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper});
      }
    };
    var removeEventListener=function(type,listener /*, useCapture (will be ignored) */) {
      var counter=0;
      while (counter&lt;eventListeners.length) {
        var eventListener=eventListeners[counter];
        if (eventListener.object==this &amp;&amp; eventListener.type==type &amp;&amp; eventListener.listener==listener) {
          if (type=="DOMContentLoaded") {
            this.detachEvent("onreadystatechange",eventListener.wrapper);
          } else {
            this.detachEvent("on"+type,eventListener.wrapper);
          }
          eventListeners.splice(counter, 1);
          break;
        }
        ++counter;
      }
    };
    Element.prototype.addEventListener=addEventListener;
    Element.prototype.removeEventListener=removeEventListener;
    if (HTMLDocument) {
      HTMLDocument.prototype.addEventListener=addEventListener;
      HTMLDocument.prototype.removeEventListener=removeEventListener;
    }
    if (Window) {
      Window.prototype.addEventListener=addEventListener;
      Window.prototype.removeEventListener=removeEventListener;
    }
  }
})();</pre>

<h3 id="Older_way_to_register_event_listeners">Older way to register event listeners</h3>

<p><code>addEventListener()</code> was introduced with the DOM 2 <a href="https://www.w3.org/TR/DOM-Level-2-Events">Events</a> specification. Before then, event listeners were registered as follows:</p>

<pre class="brush: js">
// Pass a function reference — do not add '()' after it, which would call the function!
el.onclick = modifyText;

// Using a function expression
element.onclick = function() {
  // ... function logic ...
};
</pre>

<p>This method replaces the existing <code>click</code> event listener(s) on the element if there are any. Similarly for other events and associated event handlers such as <code>blur</code> (<code>onblur</code>), <code>keypress</code> (<code>onkeypress</code>), and so on.</p>

<p>Because it was essentially part of DOM 0, this method is very widely supported and requires no special cross–browser code; hence it is normally used to register event listeners dynamically unless the extra features of <code>addEventListener()</code> are needed.</p>

<h3 id="Memory_issues">Memory issues</h3>

<pre class="brush: js">
var i;
var els = document.getElementsByTagName('*');

// Case 1
for(i=0 ; i&lt;els.length ; i++){
  els[i].addEventListener("click", function(e){/*do something*/}, false);
}

// Case 2
function processEvent(e){
  /*do something*/
}

for(i=0 ; i&lt;els.length ; i++){
  els[i].addEventListener("click", processEvent, false);
}

</pre>

<p>In the first case, a new (anonymous) function is created at each loop turn. In the second case, the same previously declared function is used as an event handler. This results in smaller memory consumption. Moreover, in the first case, since no reference to the anonymous functions is kept, it is not possible to call <code><a href="/en-US/docs/Web/API/EventTarget/removeEventListener">element.removeEventListener</a></code> because we do not have a reference to the handler, while, in the second case, it's possible to do <code>myElement.removeEventListener("click", processEvent, false)</code>.</p>

<h3 id="Improving_scrolling_performance_with_passive_listeners">Improving scrolling performance with passive listeners</h3>

<pre class="brush: js">
var elem = document.getElementById('elem');
elem.addEventListener('<code>touchmove</code>', function listener() {
  /* do something */
}, { passive: true });
</pre>

<p>This way a <code>touchmove</code> listener will not block while a user is scrolling (same applies to <code>wheel</code>&nbsp;events). Demo available <a href="https://developers.google.com/web/updates/2016/06/passive-event-listeners">here</a>&nbsp;(Google Developers Page).</p>

<div class="note">
<p><strong>Beware: </strong>Browsers&nbsp;who do not support event listener options&nbsp;will see the 3rd argument as&nbsp;<code>useCapture</code> and therefore as&nbsp;<code>true</code>.</p>
</div>

<h2 id="sect1">&nbsp;</h2>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th>Specification</th>
   <th>Status</th>
   <th>Comment</th>
  </tr>
  <tr>
   <td>{{SpecName("DOM WHATWG", "#dom-eventtarget-addeventlistener", "EventTarget.addEventListener()")}}</td>
   <td>{{Spec2("DOM WHATWG")}}</td>
   <td>&nbsp;</td>
  </tr>
  <tr>
   <td>{{SpecName("DOM4", "#dom-eventtarget-addeventlistener", "EventTarget.addEventListener()")}}</td>
   <td>{{Spec2("DOM4")}}</td>
   <td>&nbsp;</td>
  </tr>
  <tr>
   <td>{{SpecName("DOM2 Events", "#Events-EventTarget-addEventListener", "EventTarget.addEventListener()")}}</td>
   <td>{{Spec2("DOM2 Events")}}</td>
   <td>Initial definition</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<div>{{CompatibilityTable}}</div>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari (WebKit)</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>1.0<sup>[1][2]</sup></td>
   <td>{{CompatGeckoDesktop(1.0)}}<sup>[3]</sup></td>
   <td>9.0<sup>[4]</sup></td>
   <td>7</td>
   <td>1.0<sup>[1]</sup></td>
  </tr>
  <tr>
   <td><code>useCapture</code> made optional</td>
   <td>1.0</td>
   <td>{{CompatGeckoDesktop(6)}}</td>
   <td>9.0</td>
   <td>11.60</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
  <tr>
   <td><code>options</code> parameter (with <code>capture</code> and <code>passive</code> values)<sup>[5]</sup></td>
   <td>
    <p>{{CompatChrome(49.0)}} (<code>capture</code>) {{CompatChrome(51.0)}} (<code>passive</code>)</p>
   </td>
   <td>{{CompatGeckoDesktop(49)}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>Landed in Nightly {{webkitbug(158601)}}</td>
  </tr>
  <tr>
   <td><code>once</code> value in the <code>options</code> parameter</td>
   <td>{{CompatChrome(55)}}</td>
   <td>{{CompatGeckoDesktop(50)}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>Landed in Nightly {{webkitbug(149466)}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Android Webview</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
   <th>Chrome for Android</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>1.0</td>
   <td>
    <p>{{CompatVersionUnknown}}<sup>[2]</sup></p>
   </td>
   <td>{{CompatGeckoMobile(1.0)}}<sup>[3]</sup></td>
   <td>9.0</td>
   <td>6.0</td>
   <td>1.0<sup>[1]</sup></td>
   <td>
    <p>{{CompatVersionUnknown}}<sup>[2]</sup></p>
   </td>
  </tr>
  <tr>
   <td><code>useCapture</code> made optional</td>
   <td>{{CompatUnknown}}</td>
   <td>
    <p>{{CompatVersionUnknown}}</p>
   </td>
   <td>{{CompatGeckoMobile(6)}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>
    <p>{{CompatVersionUnknown}}</p>
   </td>
  </tr>
  <tr>
   <td><code>options</code> parameter (with <code>capture</code> and <code>passive</code> values)<sup>[5]</sup></td>
   <td>{{CompatNo}}</td>
   <td>{{CompatChrome(49.0)}} (<code>capture</code>) {{CompatChrome(51.0)}} (<code>passive</code>)</td>
   <td>{{CompatGeckoMobile(49)}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatChrome(49.0)}} (<code>capture</code>) {{CompatChrome(51.0)}} (<code>passive</code>)</td>
  </tr>
  <tr>
   <td><code>once</code> value in the <code>options</code> parameter</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatGeckoDesktop(50)}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
  </tr>
 </tbody>
</table>
</div>

<p>[1] Although WebKit has explicitly added <code>[optional]</code> to the <code>useCapture</code> parameter <a href="https://trac.webkit.org/changeset/89781">as recently as June 2011</a>, it had been working before the change. The new change landed in Safari 5.1 and Chrome 13.</p>

<p>[2] Before Chrome 49, the type and listener parameters were optional.</p>

<p>[3] Prior to Firefox 6, the browser would throw an error if the <code>useCapture</code> parameter was not explicitly <code>false</code>. Prior to Gecko 9.0 {{geckoRelease("9.0")}}, <code>addEventListener()</code> would throw an exception if the <code>listener</code> parameter was <code>null</code>; now the method returns without error, but without doing anything.</p>

<p>[4] Older versions of Internet Explorer support the proprietary {{domxref("EventTarget.attachEvent")}} method instead.</p>

<p>[5]&nbsp;For backwards compatibility, browsers that support&nbsp;<code>options</code> allow the third parameter to be either <code>options</code> or {{jsxref("Boolean")}}.</p>

<h2 id="See_also">See also</h2>

<ul>
 <li>{{domxref("EventTarget.removeEventListener()")}}</li>
 <li><a href="/en-US/docs/DOM/Creating_and_triggering_events">Creating and triggering custom events</a></li>
 <li><a href="https://www.quirksmode.org/js/this.html">More details on the use of <code>this</code> in event handlers</a></li>
</ul>
Revert to this revision