Element addEventListener() Method - Javascript DOM

Javascript examples for DOM:Element addEventListener

Description

The addEventListener() method attaches an event handler to the specified element.

Parameter Values

Parameter Description
event Required. name of the event.
function Required. Event handler function
useCapture Optional.

Possible values for useCapture:

  • true - The event handler is executed in the capturing phase
  • false - Default. The event handler is executed in the bubbling phase

Technical Details

Return Value:

No return value

The following code shows how to Attach a click event to a <button> element. When the user clicks on the button, output "Hello World" in a <p> element with id="demo":

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<button id="myBtn">Test</button>

<script>
document.getElementById("myBtn").addEventListener("click", function(){
    this.style.backgroundColor = "red";
});/*  ww w.  j a va 2s.c  o m*/
</script>

</body>
</html>

Related Tutorials