HTML DOM addEventListener() Method


The HTML DOM addEventListener() method is used to attach an event handler to the specified element.

Following is the syntax −

element.addEventListener(event, function, capture)

Above, the parameters include −

  • event: The name of the event. Required.
  • function: The function to run when the event occurs. Required.
  • capture: Whether the event should be executed in the capturing phase. This check and displays a boolean value; true or false.

Let us now see an example to implement the DOM addEventListener() method −

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
<h2>Demo Heading</h2>
<button id="btn">Click</button>
<p id="myid"></p>
<script>
   var x = document.getElementById("btn");
   x.addEventListener("mouseover", one);
   x.addEventListener("click", two);
   function one() {
      document.getElementById("myid").innerHTML += "Button hovered! "
   }
   function two() {
      document.getElementById("myid").innerHTML += "!!Button Clicked!! "
   }
</script>
</body>
</html>

Output

Now, if you will click, the message “Button clicked” would be displayed. On mouse hovering the button, the following text would be displayed: “Button hovered” −

Updated on: 30-Jul-2019

226 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements