Skip to main content

HTML DOM removeEventListener() method in JAVA SCRIPT

The removeEventListener() method..
The removeEventListener() method removes event handlers that have been attached with the addEventListener() method:
Note: The addEventListener() and removeEventListener() methods are not supported in IE 8 and Opera 6.0 and earlier versions so used element.attachEvent(event, function); and element.detachEvent(event, function);.
Syntax: element.removeEventListener("event",function name);
CODING:
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
    background-color:lightgreen;
    padding: 50px;
}
</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.
  <p>Click the button to remove the DIV's event handler.</p>
</div>
<button onclick="removeHandler()" id="myBtn">Try it</button>
<script>
document.getElementById("myDIV").addEventListener("mousemove", myFunction);

function myFunction() {
    var x=Math.floor((Math.random() * 100) + 1)
    document.getElementById("myDIV").style.padding =x+"px";
}

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

</body>
</html>

Comments