Java Reference
In-Depth Information
Using a declared function is also useful because it enables you to unregister an event listener with
the
removeEventListener()
method:
elementObj.removeEventListener("click", elementObjClick);
When you remove an event listener, you must provide the
same exact
information that you called
addEventListener()
with; this includes not only the same name of the event, but the same function
object that you passed to
addEventListener()
.
The beauty of the standard DOM event model is that you can register multiple event listeners for a
single event on a single element. This is extremely useful when you need to listen for the same event
on an element with different and unrelated functions. To do this, simply call
addEventListener()
as many times as you need to, like this:
elementObj.addEventListener("click", handlerOne);
elementObj.addEventListener("click", handlerTwo);
elementObj.addEventListener("click", handlerThree);
This code registers three listeners for the
click
event on the element referenced by
elementObj
.
As you may suspect, these listeners execute in the order in which they were registered. So,
when you click
elementObj
,
handlerOne()
executes first,
handlerTwo()
executes second, and
handlerThree()
executes third.
adding and removing Multiple Event Listeners
trY it out
In this Try It Out, you practice registering multiple event listeners for a single element, and you remove
those listeners when a condition is met. Type in the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 10: Example 7</title>
</head>
<body>
<img id="img0" src="usa.gif" />
<div id="status"></div>
<script>
var myImages = [
"usa.gif",
"canada.gif",
"jamaica.gif",
"mexico.gif"
];
function changeImg(e) {
var el = e.target;
var newImgNumber = Math.round(Math.random() * 3);
while (el.src.indexOf(myImages[newImgNumber]) != -1) {
newImgNumber = Math.round(Math.random() * 3);