Contents[hide] |
addEventListener
allows the registration of event listeners on the event target. An event target may be a node in a document, the document itself, a window, or an XMLHttpRequest.
target.addEventListener(type, listener, useCapture);
EventListener
interface, or simply a JavaScript
function
.
true
, useCapture
indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered listener
before being dispatched to any EventTarget
s beneath it in the DOM tree. Events which are bubbling upward through the tree will not trigger a listener designated to use capture. See
DOM Level 3 Events
for a detailed explanation.
<html>
<head>
<title>DOM Event Example</title>
<style type="text/css">
#t { border: 1px solid red }
#t1 { background-color: pink; }
</style>
<script type="text/javascript">
// Function to change the content of t2
function modifyText() {
var t2 = document.getElementById("t2");
t2.firstChild.nodeValue = "three";
}
// Function to add event listener to t
function load() {
var el = document.getElementById("t");
el.addEventListener("click", modifyText, false);
}
</script>
</head>
<body onload="load();">
<table id="t">
<tr><td id="t1">one</td></tr>
<tr><td id="t2">two</td></tr>
</table>
</body>
</html>
In the above example, modifyText()
is a listener for click
events registered using addEventListener()
. A click anywhere on the table will bubble up to the handler and run modifyText()
.
addEventListener
? addEventListener
is the way to register an event listener as specified in W3C DOM. Its benefits are as follows:
The alternative, older way to register event listeners is described below.
If an EventListener
is added to an EventTarget
while it is processing an event, it will not be triggered by the current actions but may be triggered during a later stage of event flow, such as the bubbling phase.
If multiple identical EventListener
s 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 since the duplicates are discarded, they do not need to be removed manually with the removeEventListener method.
this
within the handler It is often desirable to reference the element from which the event handler was fired, such as when using a generic handler for a series of similar elements. When attaching a function using addEventListener()
the value of this
is changed—note that the value of this
is passed to a function from the caller.
In the example above, the value of this
within modifyText()
when called from the click event is a reference to the table 't'. This is in contrast to the behavior that occurs if the handler is added in the HTML source:
<table id="t" onclick="modifyText();">
. . .
The value of this
within modifyText()
when called from the onclick event will be a reference to the global (window) object.
In IE you have to use attachEvent
rather than the standard addEventListener
. To support IE, the example above can be modified to:
if (el.addEventListener){
el.addEventListener('click', modifyText, false);
} else if (el.attachEvent){
el.attachEvent('onclick', modifyText);
}
addEventListener()
was introduced with the DOM 2 Events specification. Before then, event listeners were registered as follows:
// Using a function reference—note lack of '()'
el.onclick = modifyText;
// Using a function expression
element.onclick = function(){
...statements...
};
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.
A common way for one to stumble upon increasing memory problems is to pass an object's method as a callback:
setTimeout(obj.func, 1000); // sets wrong |this|!
document.addEventListener("load", obj.func, false); // sets wrong |this|!
A simple workaround is to pass an anonymous function as a callback:
document.addEventListener("load", function(event) { obj.func(event); }, false);
Note that this anonymous function has access to all variables in its enclosing environment, and the memory these variables use may not be reclaimed by the JavaScript engine as long as the anonymous function might be used (i.e. the event listener is registered). While only obj
need actually be preserved for the function, an engine might choose to preserve other variables, too, increasing memory overhead. Calling removeEventListener
or removing all references to an anonymous function will allow the variables' memory to be reclaimed, and you should be careful to do so to allow unused memory to be efficiently reclaimed by the JavaScript engine.