Java Reference
In-Depth Information
This code is reminiscent of the past few examples; so, let's just focus on what's different. First, the
HTML:
<img id="img0" src="usa.gif" />
<div id="status"></div>
Instead of two image elements, this HTML defines a single
<img/>
element with an
id
of
img0
and
a
<div/>
element whose
id
is
status
. The contents of the
<div/>
element will change when the user
clicks the image.
There's a new function called
updateStatus()
, and its purpose is to update the text inside
<div id="status"/>
. The first two lines of this function acquire references to the event target (the
image) and
<div/>
element:
function updateStatus(e) {
var el = e.target;
var status = document.getElementById("status");
The next line of code changes the text of the
status
element:
status.innerHTML = "The image changed to " + el.src;
Element objects have an
innerHTML
property that lets you set the contents of the element to whatever
value you assign to it. In this code, you change the
<div/>
element's contents to contain the URL of the
picture currently displayed in the browser.
To add some variety, the next few lines of code remove the image's click
event
listeners if the Mexico
flag is displayed in the browser:
if (el.src.indexOf("mexico") > -1) {
el.removeEventListener("click", changeImg);
el.removeEventListener("click", updateStatus);
}
}
The
if
statement uses the
indexOf()
method on the image's
src
to determine if the Mexico flag is
currently displayed. If so, you remove the image's two event listeners using the
removeEventListener()
method. We have yet to discuss the code for registering these
click
event listeners, but you pass the
same information to
removeEventListener()
that you pass to
addEventListener()
. If you don't, you
won't remove the event listeners.
The final lines of code set up the event listeners:
var imgObj = document.getElementById("img0");
imgObj.addEventListener("click", changeImg);
imgObj.addEventListener("click", updateStatus);
The first line retrieves the
<img id="img0" />
element, and you register the
click
event handlers by
calling
addEventListener()
and passing
click
for the event and the two functions,
changeImg()
and
updateStatus()
, respectively.