addEventListener
Summary
Registers an event handler for the specified event type.
Method of dom/EventTargetdom/EventTarget
Syntax
target.addEventListener(type, handler, useCapture);
Parameters
type
- Data-type
- String
The type of event type to register.
handler
- Data-type
- function
A function that is called when the event is fired.
useCapture
- Data-type
- Boolean
(Optional)
A Boolean value that specifies the event phase to add the event handler for.
While this parameter is officially optional, it may only be omitted in modern browsers.
Return Value
No return value
Examples
This example listens to any click events on the document or its descendants.
document.addEventListener(
"click",
function (e) {
console.log("A " + e.type + " event was fired.");
},
false);
Notes
- Events are handled in two phases: capturing and bubbling. During the capturing phase, events are dispatched to parent objects before they are dispatched to event targets that are lower in the object hierarchy. During the bubbling phase, events are dispatched to target elements first and then to parent elements. You can register event handlers for either event phase. For more information, see eventPhase.
- Some events, such as onfocus, do not bubble. However, you can capture all events. You cannot capture events by elements that are not parents of the target element.
- If you register multiple identical event handlers on the same event target, the duplicate event handlers are discarded.
Related specifications
- DOM Level 3 Events
- Working Draft
Attributions
Microsoft Developer Network: [Windows Internet Explorer API reference Article]