How to add an event handler to an element in JavaScript HTML DOM?

JavascriptObject Oriented ProgrammingFront End Technology

To add an event handler to an element, use the JavaScript addEventListener() method. You can try to run the following code to add event handler −

Example

<!DOCTYPE html>
<html>
   <body>
      <p>Click the below button.</p>
      <button id = "btnid">Click me</button>

      <p id = "pid"></p>

      <script>
         document.getElementById("btnid").addEventListener("click", displayEvent);

         function displayEvent() {
            document.getElementById("pid").innerHTML = Date();
         }
      </script>
   </body>
</html>
raja
Published on 27-Feb-2018 16:04:08
Advertisements