Os nossos voluntários ainda não traduziram este artigo para Português (Europeu). Junte-se a nós e ajude-nos a fazer o trabalho!
Pode também ler o artigo em English (US).

The EventTarget method addEventListener() sets up a function that will be called whenever the specified event is delivered to the target. Common targets are Element, Document, and Window, but the target may be any object that supports events (such as XMLHttpRequest).

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.

Syntax

target.addEventListener(type, listener[, options]);
target.addEventListener(type, listener[, useCapture]);
target.addEventListener(type, listener[, useCapture, wantsUntrusted  ]); // Gecko/Mozilla only

Parameters

type
A case-sensitive string representing the event type to listen for.
listener
The object which receives a notification (an object that implements the Event interface) when an event of the specified type occurs. This must be an object implementing the EventListener interface, or a JavaScript function. See The event listener callback for details on the callback itself.
options Optional
An options object that specifies characteristics about the event listener. The available options are:
  • capture: A Boolean indicating 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 Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.
  • passive: A Boolean which, if 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. See Improving scrolling performance with passive listeners to learn more.
  • mozSystemGroup: A Boolean indicating that the listener should be added to the system group. Available only in code running in XBL or in the chrome of the Firefox browser.
useCapture Optional
A Boolean indicating whether 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 which 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. Events in the target phase will trigger all listeners on an element in the order they were registered, regardless of the useCapture parameter.
Note: useCapture has not always been optional. Ideally, you should include it for the widest possible browser compatibility.
wantsUntrusted
A Firefox (Gecko)-specific parameter. If true, the listener receives synthetic events dispatched by web content (the default is false for browser chrome and true for regular web pages). This parameter is useful for code found in add-ons as well as the browser itself. See Interaction between privileged and non-privileged pages for an example.

Before using a particular value in the options object, 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. See Safely detecting option support for details.

Return value

undefined

Usage notes

The event listener callback

The event listener can be specified as either a callback function or as an object that implements EventListener, 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 which 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 /* fullscreenerror */ {
    /* 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 which 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:

var passiveSupported = false;

try {
  var options = Object.defineProperty({}, "passive", {
    get: function() {
      passiveSupported = true;
    }
  });

  window.addEventListener("test", options, options);
  window.removeEventListener("test", options, 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.

Example

Add a simple listener

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

HTML

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

JavaScript

// 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);

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

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

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

JavaScript

// 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);

Notice that the listener is an anonymous function that encapsulates code that is then, in turn, able to send parameters to the modifyText() 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

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

JavaScript

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

Result

Please note that while anonymous and arrow functions are similar, they have different this bindings. While anonymous (and all traditional JavaScript functions) create their own this bindings, arrow functions inherit the this binding 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.

Other notes

Why use addEventListener?

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

  • It allows adding more than a single handler for an event. This is particularly useful for AJAX libraries, JavaScript modules, or any other kind of code that needs to work well with other libraries/extensions.
  • It gives you finer-grained control of the phase when the listener is 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.

If 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 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 which binds the value of this in a manner consistent with the 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. This is shown in the following example:

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

The value of this within modifyText() is a reference to the global object Window (or undefined in the case of strict mode).

Specifying this using bind()

The Function.prototype.bind() method lets you specify the value that should be used as this for all calls to a given function. This 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 remove it later.

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

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

Another way of handling the reference to this is to pass to the EventListener a function that calls the method of the object which contains the fields that need to be accessed:

class SomeClass {

  constructor() {
    this.name = 'Something Good';
  }

  register() {
    var that = this;
    window.addEventListener('keydown', function(e) {return that.someMethod(e);});
  }

  someMethod(e) {
    console.log(this.name);
    switch(e.keyCode) {
      case 5:
        // some code here...
        break;
      case 6:
        // some code here...
        break;
    }
  }

}

var myObject = new SomeClass();
myObject.register();

Legacy Internet Explorer and attachEvent

In Internet Explorer versions before IE 9, you have to use attachEvent(), rather than the standard addEventListener(). For IE, we 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 addEventListener(), removeEventListener(), Event.preventDefault(), and Event.stopPropagation() not being supported by Internet Explorer 8 by 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. The following code only adds IE 8 support. This IE 8 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:

// Passing 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. Other events and associated event handlers such as blur (onblur) and keypress (onkeypress) behave similarly.

Because it was essentially part of DOM 0, this technique for adding event listeners is very widely supported and requires no special cross–browser code. 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 with each iteration of the loop. 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, it is not possible to call removeEventListener() because no reference to the anonymous function is kept. In the second case, it's possible to do myElement.removeEventListener("click", processEvent, false).

Improving scrolling performance with passive listeners

According to the specification, the default value for the passive option is always false. However, this introduces the potential for event listeners handling certain touch events (among others) to block the browser's main thread while it is attempting to handle scrolling, resulting in possibly enormous reduction in performance during scroll handling.

To prevent this problem, some browsers (specifically, Chrome and Firefox) have changed the default value of the passive option to true for the touchstart and touchmove events on the document-level nodes Window, Document, and Document.body. This prevents the event listener from being called, so it can't block page rendering while the user is scrolling.

Note: See the compatibility table below if you need to know which browsers (and/or which versions of those browsers) implement this altered behavior.

You can override this behavior by explicitly setting the value of passive to false, as shown here:

/* Feature detection */
var passiveSupported = false;

try {
  window.addEventListener("test", null, Object.defineProperty({}, "passive", { get: function() { passiveSupported = true; } }));
} catch(err) {}

/* Event Listener */
var elem = document.getElementById('elem');

elem.addEventListener('touchmove', function listener() {
  /* do something */
}, passiveSupported ? { passive: false } : false);

On older browsers that don't support the options parameter to addEventListener(),  attempting to use it prevents the use of the useCapture argument without proper use of feature detection.

You don't need to worry about the value of passive for the basic scroll event. Since it can't be canceled, event listeners can't block page rendering anyway.

Specifications

Specification Status Comment
DOM
The definition of 'EventTarget.addEventListener()' in that specification.
Living Standard  
DOM4
The definition of 'EventTarget.addEventListener()' in that specification.
Obsolete  
Document Object Model (DOM) Level 2 Events Specification
The definition of 'EventTarget.addEventListener()' in that specification.
Obsolete Initial definition

Browser compatibility

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support11121

9

Yes2 3

71
useCapture parameter made optional1 Yes6911.6 Yes
Form with options object supported (third parameter can be either options or a Boolean, for backwards compatibility)49 Yes49 No Yes10
options: capture option52 Yes Yes No Yes Yes
options: once option55 Yes50 No42 Yes
options: passive option51 Yes Yes No Yes Yes
options: passive option defaults to true for touchstart and touchmove events55 No61 No ? No
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidOpera AndroidiOS SafariSamsung Internet
Basic support1111 Yes471 Yes
useCapture parameter made optional11 Yes611.6 Yes Yes
Form with options object supported (third parameter can be either options or a Boolean, for backwards compatibility)4949 Yes49 Yes105.0
options: capture option5252 Yes Yes Yes Yes6.0
options: once option5555 Yes5042 Yes6.0
options: passive option5151 Yes Yes Yes Yes5.0
options: passive option defaults to true for touchstart and touchmove events5555 No61 ? No6.0

1. Before Chrome 49, the type and listener parameters were optional.

2. Older versions of IE supported an equivalent, proprietary, EventTarget.attachEvent() method.

3. Supported as attachEvent.

See also