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.
The addEventListener()
method attaches an event handler to an element.
The removeEventListener() Method
The removeEventListener() Method
element.addEventListener(
event,
function,
useCapture)
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. |
NONE |
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 »
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 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!