Window addEventListener()
Examples
Add a click event handler to the window:
window.addEventListener("click", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
Try it Yourself »
Simpler syntax:
window.addEventListener("click", function(){
document.getElementById("demo").innerHTML = "Hello World";
});
Try it Yourself »
More examples below.
Description
The addEventListener()
method attaches an event handler to a window.
Document Methods
The removeEventListener() Method
Element Methods
The removeEventListener() Method
Tutorials
Syntax
window.addEventListener(event, function, Capture)
Parameters
Parameter | Description |
event | Required. The event name. Do not use the "on" prefix. Use "click" instead of "onclick". All HTML DOM events are listed in the: HTML DOM Event Object Reference. |
function | Required. The function to run when the event occurs. When the event occurs, an event object is passed to the function as the first parameter. The type of the event object depends on the specified event. For example, the "click" event belongs to the MouseEvent object. |
capture |
Optional (default = false).true - The handler is executed in the capturing phase.false - The handler is executed in the bubbling phase.
|
Return Value
NONE |
More Examples
You can add many event listeners to a window:
window.addEventListener("click", myFunction1);
window.addEventListener("click", myFunction2);
Try it Yourself »
You can add different types of events:
window.addEventListener("mouseover", myFunction);
document.addEventListener("click", someOtherFunction);
window.addEventListener("mouseout", someOtherFunction);
Try it Yourself »
When passing parameters, use an "anonymous function" to call a function with the parameters:
window.addEventListener("click", function() {
myFunction(p1, p2);
});
Try it Yourself »
Change the background color of a document:
window.addEventListener("click", function(){
document.body.style.backgroundColor = "red";
});
Try it Yourself »
Using the removeEventListener() method:
// Add an event listener
window.addEventListener("mousemove", myFunction);
// Remove the event listener
window.removeEventListener("mousemove", myFunction);
Try it Yourself »
Browser Support
addEventListener
is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.