How to remove event handlers in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

Javascript provides removeEventListener() method to remove event handlers. An event is handled through addEvenetListener() method. The removeEventListener() method removes event handlers that have been attached with that addEventListener() method.


Live Demo

   <h3 id="add">Hover me </h3>
   <p id="remove"> </p>
   <h3>Click this button to stop hovering effect </h3>
   <input type ="button" id="clickIt" onclick="RespondClick()" value ="remove">
      const listener = document.getElementById("add");
      listener.addEventListener("mouseover", RespondMouseOver);
      function RespondMouseOver() {
         document.getElementById("remove").innerHTML += 1+ "</br>";
      function RespondClick() {
         listener.removeEventListener("mouseover", RespondMouseOver);
         document.getElementById("remove").innerHTML += 0;

When we executed the above code we will get the following displayed on the screen

If we hover on the "Hover me" text then 1's will appear. The number of times we hover, the number of times 1's are produced. When we hover the text for 4 times we get the following executed on the screen.


To stop the event handler, we have to click on the "remove" button. After clicking on the remove button we get '0' displayed on the screen and later on even though we hover on the text no 1's will be produced as shown in the figure.

Updated on 30-Jun-2020 09:21:27