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 −


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

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

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

         function displayEvent() {
            document.getElementById("pid").innerHTML = Date();
Published on 27-Feb-2018 11:34:08