EventTarget.addEventListener()

Diese Übersetzung ist unvollständig. Bitte helfen Sie, diesen Artikel aus dem Englischen zu übersetzen.

Die EventTarget.addEventListener() Methode registriert den angegebenen "Zuhörer" (Engl. "listener") an einem ausgewählten EventTarget, auf welches es aufgerufen wird. Das Event-Ziel ist vielleicht ein Element in einem Dokument, das Document selbst, ein Window Objekt, oder irgendein anderes Objekt, welches Events unterstützt (wie z.B. XMLHttpRequest).

Syntax

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

Parameter

type
Ein String repräsentiert den event type auf welches es hören soll.
listener
Das Objekt, welches eine Benachrichtigung erhält (ein Objekt, welches die Event Schnittstelle implementiert), wenn ein Event des angegebenen Typs auftritt. Es muss ein Objekt sein, welches die EventListener Schnittstelle implementiert, oder einfach eine JavaScript Funktion.
options Optional
Ein optionales Objekt das den Charakter des event listener spezifiziert. Die möglichen Optionen sind:
  • capture: Ein Boolean, der angibt, dass Ereignisse dieses Typs an den registrierten listener geschickt werden, bevor er in ein EventTarget darunter im DOM-Baum geschickt wird.
  • once: Ein Boolean, der angibt, dass der Zuhörer höchstens einmal nach dem Hinzufügen aufgerufen werden sollte. Wenn es true ist, würde der Zuhörer automatisch entfernt werden, sobald er aufgerufen wird.
  • passive: Ein Boolean, der angibt, dass der Zuhörer niemals preventDefault() aufruft. Wenn dies der Fall ist, sollte der User-Agent es ignorieren und eine Konsolenwarnung generieren.
  • mozSystemGroup: Verfügbar nur in Code der in XBL oder in Firefox's Chrom läuft. Es ist ein Boolean welcher definiert ob der Zuhörer der Systemgruppe hinzugefügt wurde.
useCapture Optional
Ein Boolean der angibit das ein Event dieses Typs zu einem registrierten listener versandt wird, bevor es zu irgendein EventTarget im DOM-Baum versandt wird. Events die den Baum aufwärts "blubbern" (eng. "bubbling") werden keinen listener auslösen der erstellt wurde um Events einzufangen (capture). Events die "blubbern" (bubbling) und erfassen (capture) sind zwei Arten von Ereignissen, die in einem ausbreitenden Elemente auftreten, das innerhalb eines anderen Elements verschachtelt ist, wenn die beiden Elemente einen handler für dieses Ereignis registriert haben. Der Event-Ausbreitungsmodus bestimmt die Reihenfolge in den Elemente das Ereignis entgegenehmen.
Siehe DOM Level 3 Events und JavaScript Event-Reihenfolge für detailierte Erläuterung. Wenn nichts angegeben, useCapture wird false als Standard gesetzt.
Notiz: Für Event-Hörer, die an das Event-Ziel angeschlossen sind; Das Ereignis ist in der Zielphase, anstatt zu erfassen und Blubbernden-Phasen. Ereignisse in der Zielphase lösen alle Zuhörer auf einem Element aus, unabhängig vom useCapture-Parameter.
Notiz: useCapture wurde nur in neueren Versionen der großen Browser freigegeben; Zum Beispiel war es nicht optional vor Firefox 6. Sie sollten diesen Parameter für die breiteste Kompatibilität zur Verfügung stellen.
wantsUntrusted
Wenn true, erhält der Zuhörer synthetische Ereignisse, die durch Webinhalte versendet werden (der Standard ist false für Chrome und gilt für regelmäßige Webseiten). Dieser Parameter ist nur in Gecko verfügbar und ist vor allem für den Code in Add-ons und den Browser selbst nützlich. Siehe Interaktion zwischen privilegierten und nicht privilegierten Seiten für Beispiele.

Beispiele

Hinzufügen eines simplen Event-Listener

HTML Inhalt

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

JavaScript Inhalt

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

Notizen

Wieso sollte man addEventListener nutzen?

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.

Hinzufügen eines Zuhörers während des Ereignisversands

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.

Mehrere identische event listener

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.

Der Wert davon im 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.

Dies ist ein Beispiel mit und ohne 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);

Another way of handling the reference to this is to pass to the EventListener a function which calls the method of the object which fields want 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, 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 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 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), keypress (onkeypress), and so on behave similarly.

Because it was essentially part of DOM 0, this method 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 at 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 element.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

The default value for the passive option is false. Starting in Chrome 56 (desktop, Chrome for android, and android webview) the default value for touchstart and touchmove is true and calls to preventDefault() are not needed. To override this behavior, you simply set the passive option to false as shown in the example below. This change prevents the listener from blocking page rendering while a user is scrolling. A demo is available on the Google Developer site. 

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

Spezifikationen

Spezification Status Kommentar
DOM
Die Definition von 'EventTarget.addEventListener()' in dieser Spezifikation.
Lebender Standard  
DOM4
Die Definition von 'EventTarget.addEventListener()' in dieser Spezifikation.
Empfehlung  
Document Object Model (DOM) Level 2 Events Specification
Die Definition von 'EventTarget.addEventListener()' in dieser Spezifikation.
Empfehlung Initial definition

Browserkompatibilität

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 1.0[1][2] (Ja) 1.0 (1.7 oder früher)[3] 9.0[4] 7 1.0[1]
useCapture made optional 1.0 (Ja) 6 (6) 9.0 11.60 (Ja)
options parameter (with capture and passive values)[5]

49.0 (capture) 51.0 (passive)

Nicht unterstützt 49 (49) Nicht unterstützt (Ja) Landed in Nightly WebKit Bug 158601
once value in the options parameter 55 Nicht unterstützt 50 (50) Nicht unterstützt 42 Landed in Nightly WebKit Bug 149466
Passive defaults to true for touchstart and touchend 55 Nicht unterstützt Nicht unterstützt Nicht unterstützt Nicht unterstützt Nicht unterstützt
Feature Android Webview Chrome for Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support

(Ja)[2]

(Ja)

(Ja) 1.0 (1.0)[3] 9.0 6.0 1.0[1]
useCapture made optional

(Ja)

(Ja)

(Ja) 6.0 (6) ? ? ?
options parameter (with capture and passive values)[5] 49.0 (capture) 51.0 (passive) 49.0 (capture) 51.0 (passive) Nicht unterstützt 49.0 (49) ? (Ja) ?
once value in the options parameter 55 55 Nicht unterstützt 50 (50) Nicht unterstützt 42 ?
Passive defaults to true for touchstart and touchend 55 55 Nicht unterstützt Nicht unterstützt Nicht unterstützt Nicht unterstützt Nicht unterstützt

[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 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6), 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 EventTarget.attachEvent method instead.

[5] For backwards compatibility, browsers that support options allow the third parameter to be either options or Boolean.

Siehe auch

Schlagwörter des Dokuments und Mitwirkende

 Mitwirkende an dieser Seite: Aragur, StevenS77
 Zuletzt aktualisiert von: Aragur,