Javascript Reference - HTML DOM removeEventListener() Method








The removeEventListener() method removes an event handler that has been attached with the addEventListener() method.

Browser Support

removeEventListener Yes 9.0 Yes Yes Yes

Syntax

element.removeEventListener(event, function, useCapture) 

Parameter Values

Parameter Description
event Required. The name of the event to remove.
function Required. The function to remove.
useCapture Optional. The event phase to remove the event handler from.

Possible values:
  • true - Removes the event handler from the capturing phase
  • false- Default. Removes the event handler from the bubbling phase




Return Value

No return value

Example

The following code shows how to remove a "mousemove" event that has been attached with the addEventListener() method.


<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {<!--   ww  w. j av a 2s  . c  om-->
    background-color: coral;
    border: 1px solid;
    padding: 50px;
    color: white;
}
</style>
</head>
<body>

<div id="myDIV">test.
  <button onclick="removeHandler()" id="myBtn">test</button>
</div>

<p id="demo"></p>

<script>
document.getElementById("myDIV").addEventListener("mousemove", myFunction);

function myFunction() {
    document.getElementById("demo").innerHTML = Math.random();
}

function removeHandler() {
    document.getElementById("myDIV").removeEventListener("mousemove", myFunction);
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code removes event listener from a button click event.

<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
p {<!--from  w  ww  .  j ava2s . c  o m-->
  background: gray;
  color: white;
  padding: 10px;
  margin: 5px;
  border: thin solid black
}
</style>
</head>
<body>
  <p>This is a test.</p>
  <p id="block2">This is a test.</p>
  <button id="pressme">Press Me</button>
  <script type="text/javascript">
    var pElems = document.getElementsByTagName("p");
    for ( var i = 0; i < pElems.length; i++) {
      pElems[i].addEventListener("mouseover", handleMouseOver);
      pElems[i].addEventListener("mouseout", handleMouseOut);
    }
    document.getElementById("pressme").onclick = function() {
      document.getElementById("block2").removeEventListener("mouseout",handleMouseOut);
    }
    function handleMouseOver(e) {
        e.target.innerHTML += "mouseover";
      e.target.style.background = 'red';
      e.target.style.color = 'black';
    }
    function handleMouseOut(e) {
        e.target.innerHTML += "mouseout";
      e.target.style.removeProperty('color');
      e.target.style.removeProperty('background');
    }
  </script>
</body>
</html>

Click to view the demo