HTML DOM Element addEventListener()
Examples
Add a click event to a <button> element:
element.addEventListener("click", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
Try it Yourself »
More compact code:
element.addEventListener("click", function() {
document.getElementById("demo").innerHTML = "Hello World";
});
Try it Yourself »
More examples below.
Description
The addEventListener()
method attaches an event handler to an element.
Element Methods
The removeEventListener() Method
Document Methods
The removeEventListener() Method
Tutorials
Syntax
element.addEventListener(event, function, useCapture)
Parameters
Parameter | Description |
event | Required. The name of the event. Do not use the "on" prefix. Use "click" not "onclick". The Complete List of DOM Events. |
function | Required. The function to run when the event occurs. |
useCapture |
Optional (default = false).false - The handler is executed in the bubbling phase.true - The handler is executed in the capturing phase.
|
Return Value
NONE |
More Examples
You can add many events to the same element:
element.addEventListener("click", myFunction1);
element.addEventListener("click", myFunction2);
Try it Yourself »
You can add different events to the same element:
element.addEventListener("mouseover", myFunction);
element.addEventListener("click", someOtherFunction);
element.addEventListener("mouseout", someOtherFunction);
Try it Yourself »
To pass parameter values, use an "anonymous function":
element.addEventListener("click", function() {
myFunction(p1, p2);
});
Try it Yourself »
Change the background color of a <button> element:
element.addEventListener("click", function() {
this.style.backgroundColor = "red";
});
Try it Yourself »
The difference between bubbling and capturing:
element1.addEventListener("click", myFunction, false);
element2.addEventListener("click", myFunction, true);
Try it Yourself »
Remove an event handler:
element.addEventListener("mousemove", myFunction);
element.removeEventListener("mousemove", myFunction);
Try it Yourself »
Browser Support
element.addEventListener()
is a DOM Level 2 (2001) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.