English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
element.addEventListener()The method attaches an event handler to the specified element.
Useelement.removeEventListener()The method removes the event handler attached with addEventListener() method.
Usedocument.addEventListener()The method attaches an event handler to the document.
element.addEventListener(event, listener, useCapture)
var x = document.querySelector("button"); x.addEventListener("click", function() { alert("Hello World!!!"); });Test See </›
The numbers in the table specify the first browser version that fully supports the addEventListener() method:
Method | |||||
addEventListener() | 1 | 1 | 7 | 1.0 | 9 |
Parameter | Description |
---|---|
event | (Required) The event can be any valid JavaScript event. Do not use the "on" prefix when using events, such as using "click" instead of "onclick" or "mousedown" instead of "onmousedown". For a list of all HTML DOM events, please refer to our completeHTML DOM event object reference. |
listener | (Required) It can be a JavaScript function that responds to the event occurrence. When an event occurs, the event object is passed as the first argument to the function. The type of the event object depends on the specified event. For example, the "click" event belongs to the MouseEvent object. |
useCapture | (Optional) A boolean value that specifies whether the event is executed during the capturing phase or the bubbling phase. The default is false. Possible values:
You can find more information on ourIn the JavaScript event propagation tutorialRead more about event propagation |
Return value: | None |
---|---|
DOM version: | DOM 2Level |
This example references an external "named" function:
document.querySelector("button").addEventListener("click", myFunc); function myFunc() { document.body.style.backgroundColor = "coral";Test See </›
You can add many events to an element without overwriting existing events:
document.querySelector("button").addEventListener("click", myFunc); document.querySelector("button").addEventListener("click", anotherFunc);Test See </›
You can add different types of events to elements:
document.querySelector("button").addEventListener("mouseenter", myFunc1); document.querySelector("button").addEventListener("click", myFunc2); document.querySelector("button").addEventListener("mouseout", myFunc3);Test See </›
When passing parameter values, please use an anonymous function that calls the specified function with the parameters:
var btn = document.querySelector("button"); btn.addEventListener("click", function() { myFunc(x, y); });Test See </›
JavaScript Tutorial:Event Listener
JavaScript Tutorial:Event Propagation
HTML DOM Reference:element.removeEventListener()
HTML DOM Reference:document.addEventListener()