/

HTML / CSS / JavaScript Tutorial

JavaScript DOM HTML method: removeEventListener()

[this page | pdf | back links]

The removeEventListener() method (when applied to HTML elements in the JavaScript DOM) removes (detaches) an event handler from the element.

 

It has the following syntax with the following parameters. It does not return any value.

 

element.removeEventListener(event, function, useCapture)

 

Parameter

Required / Optional

Description

event

Required

String specifying event (excluding the ‘on’ part at the start of the relevant event attribute name)

function

Required

Name of function (with ‘()’ included at end)

useCapture

Optional

If true then event handler is executed in the capturing phase of the page load, if false then in the bubbling phase

 

Some earlier versions of some major browsers do not support this method. For these browsers you instead need to use the detachEvent() method. If the event listener was attached two times, once in the capturing and ones in the bubbling phase using the useCapture parameter then it needs to be removed twice as well.

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,td,tr,th,caption {border: thin solid black; border-collapse: collapse;}
div {width: 200px; height: 30px; background-color: orange; border: thin solid green;} 
</style>
</head>
<body>
An event listener that responds to clicking on the highlighted box
is added when the page loads, but after several clicks is removed<br><br>

<div id="element"></div><br>
<table>
  <tr><th>Dom Html method</th><th>Value returned</th></tr>
  <tr><td>AddEventListener<br>RemoveEventListener</td><td id="x1"></td></tr>
</table>

<script>
var y = document.getElementById("element");
y.addEventListener("click", addevent, false)
var x = 0
function addevent() {
  x = x + 1;
  document.getElementById("x1").innerHTML = "<b>clicked " + x + "</b>";
  if (x>=3) {
    y.removeEventListener("click", addevent);
  }
}
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodDomHtmlRemoveEventListener() {
  var z = document.createElement("TABLE"); return !!z.removeEventListener;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)


Desktop view | Switch to Mobile