Javascript DOM HTML Document removeEventListener() Method vs detachEvent() method

Introduction

For browsers that do not support the removeEventListener() method, you can use the detachEvent() method.

This example demonstrates a cross-browser solution:

Click the button to remove the event handler.

View in separate window

<!DOCTYPE html>
<html>
<body>
<button onclick="removeHandler()" id="myBtn">Test</button>
<p id="demo"></p>

<script>
if (document.addEventListener) {/*from w w w. j  a v  a  2s  . c o m*/
  document.addEventListener("mousemove", myFunction);
} else if (document.attachEvent) {
  document.attachEvent("onmousemove", myFunction);
}

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

function removeHandler() {
  if (document.removeEventListener) {
    document.removeEventListener("mousemove", myFunction);
  } else if (document.detachEvent) {
    document.detachEvent("onmousemove", myFunction);
  }
}
</script>

</body>
</html>



PreviousNext

Related