The following code example shows how to Add an Event Listener in JavaScript.

Programmingempire

Example Code to Demonstrate How to Add an Event Listener in JavaScript

In order to add an event listener dynamically, we use the function addEventListener(). As can be seen in the example, the JavaScript function f1() is added when the user moves mouse curser over a paragraph. As a result, the function first retrieves the button using getElementById() method. Further, it calls the addEventListener() function that adds an event handler function to the click event.

<html>
<head>
  <title>Adding an Event Listener</title>
  <script>
     function f1()
     {
        var v=document.getElementById("b1");
        v.addEventListener("click", function(){
            alert('The Button is Clicked!')});
     }
  </script>
</head>
<body>
  <div style="margin: 50px; padding: 20px; text-align: center;
      font-size: 20px;">
     Move the mouse curser on below text to make the button clickable!
     <br/><br/>
     <p onmouseover="f1()">Add Click Event Listener to the Button</p>
     <button id="b1">Click Me</button>
  </div>
</body>
</html>

Output

The Output of the Example to Demonstrate how to Add an Event Listener in JavaScript
The Output of the Example to Demonstrate how to Add an Event Listener in JavaScript

Further Reading

Python List Practice Exercise

programmingempire