HTML DOM Document addEventListener()

Examples

Add a click event to the document:

document.addEventListener("click", myFunction);

function myFunction() {
  document.getElementById("demo").innerHTML = "Hello World";
}
Try it Yourself »

Simpler syntax:

document.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 document.


Syntax

document.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 the document:

document.addEventListener("click", myFunction1);
document.addEventListener("click", myFunction2);
Try it Yourself »

You can add different types of events:

document.addEventListener("mouseover", myFunction);
document.addEventListener("click", someOtherFunction);
document.addEventListener("mouseout", someOtherFunction);
Try it Yourself »

When passing parameters, use an "anonymous function" to call a function with the parameters:

document.addEventListener("click", function() {
  myFunction(p1, p2);
});
Try it Yourself »

Change the background color of the document:

document.addEventListener("click", function(){
  document.body.style.backgroundColor = "red";
});
Try it Yourself »

Using the removeEventListener() method:

// Add an event listener
document.addEventListener("mousemove", myFunction);

// Remove event listener
document.removeEventListener("mousemove", myFunction);
Try it Yourself »

Browser Support

document.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.