How to remove event listener with JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

Use the removeEventListener() method in JavaScript to remove event handler attached with addEventListener() method.

Example

<!DOCTYPE html>
<html>
   <head>
      <style>
         #box {
            background-color: gray;
            border: 2px dashed;
         }
      </style>
   </head>
   <body>
      <div id="box">Demo Text!
         <p>Click below to remove event handler.</p>
         <button onclick="removeEvent()" id="btnid">Remove</button>
      </div>
      <p id="pid"> </p>
      <script>
         document.getElementById("box").addEventListener("mousemove", display);
         function display() {
            document.getElementById("pid").innerHTML = Math.random();
         }
         function removeEvent() {
            document.getElementById("box").removeEventListener("mousemove", display);
         }
      </script>
   </body>
</html>
raja
Published on 27-Feb-2018 15:45:55
Advertisements