Javascript DOM HTML Element addEventListener() Method with removeEventListener() method

Introduction

Using the removeEventListener() method to remove an event handler that has been attached with the addEventListener() method:

Click the button to remove the DIV's event handler.

View in separate window

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

<div id="myDIV">This div element has an onmousemove event handler that displays a random number every time you move your mouse inside this orange field.

  <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>



PreviousNext

Related