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 addEventListener() Method
The removeEventListener() Method
Element Methods
The addEventListener() Method
The removeEventListener() Method
Tutorials
HTML DOM EventListener
The Complete List of DOM Events
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
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:
Contact Sales
If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]
Report Error
If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our
terms of use
,
cookie and privacy policy
.
W3Schools is Powered by W3.CSS
.