Computer >> Computer tutorials >  >> Programming >> Javascript

How to add many Event Handlers to the same element with JavaScript HTML DOM?


To add more than one event handler to the same element, use the addEventListener() more than once. For each event handler, you need to add an addEventListener() method.

Example

You can try to run the following code to learn how to add more than one event handler −

<!DOCTYPE html>
<html>
   <body>
      <p>Click the below button once to get Date.</p>
      <p>Click the below button twice to get an alert box.</p>
      <button id="btnid"> Click me </button>
      <p id="pid"></p>
   
      <script>
         document.getElementById("btnid").addEventListener("click", displayEvent);
         var res = document.getElementById("btnid");
         res.addEventListener("dblclick", myFunction);
         function displayEvent() {
            document.getElementById("pid").innerHTML = Date();
         }
         function myFunction() {
            alert ("You clicked the button twice!");
         }
      </script>
   </body>
</html>