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

JavascriptObject Oriented ProgrammingFront End Technology

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>
raja
Published on 27-Feb-2018 16:14:29
Advertisements