How to add an event handler to the specified element in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

Javascript provides the addEventListener() method that attaches an event handler to the specified element. This method attaches an event handler to an element without overwriting existing event handlers. At a time it is possible to add many event handlers to an element.

The addEventListener() method makes it easier to control how the event reacts to bubbling. We can apply many events such as mouseover, click, etc.


In the following example, the mouseover event is assigned. So when we place a mouse on the button, we will get the requested text as shown in the output.

 Live Demo

<p>This example uses the addEventListener() method to attach a mouseover event to a button.</p>
<input type = "button" id="myBtn" value = "listener">
<p id="listener"></p>
   document.getElementById("myBtn").addEventListener("mouseover", displayText);
   function displayText() {
      document.getElementById("listener").innerHTML =
      document.write("Tutorix is the best e-learning platform");

When we execute the above code we will get the following displayed on the screen.

When we mouseover on the "listener" button, then the following output is executed.


Published on 09-Jul-2019 12:10:58