HTML, CSS, JavaScript Tutorial

/

JavaScript Document own method: addEventListener()

[this page | pdf | back links]

The addEventListener() method (when
applied to the document object of the JavaScript
DOM) attaches
an event handler to the document.

 

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

 

document.addEventListener(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 attachEvent()
method.

 

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;}
</style>
</head>
<body>
An event listener that responds to clicking anywhere on the document
is added when the page loads, but after several clicks is removed<br><br>
<table >
  <tr><th>Dom method</th><th>Value returned</th></tr>
  <tr><td>AddEventListener<br>RemoveEventListener</td><td id="x1"></td></tr>
</table>

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

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:

function isSupportedJavaScriptMethodDomAddEventListener() {
  return !!document.addEventListener;
}

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