This example uses the addEventListener()
method to attach a click event to the document.
Attach a click event to the document.
When the user clicks anywhere in the document, output "Hello World" in a <p> element with id="demo":
<!DOCTYPE html> <html> <body> <p>Click anywhere in the document.</p> <p id="demo"></p> <script> document.addEventListener("click", function(){ document.getElementById("demo").innerHTML = "Hello World!"; });//from w w w . j a va 2 s .c om </script> </body> </html>
The document.addEventListener()
method attaches an event handler to the document.
document.addEventListener(event, function[,useCapture]);
Parameter Values
Parameter | Description |
---|---|
event | Required. A String name of the event. |
function | Required. Specifies the function to run when the event occurs. |
useCapture | Optional. Possible values: true - The event handler is executed in the capturing phase false - Default. The event handler is executed in the bubbling phase |