Java Reference
In-Depth Information
In the first line of the function, you set the
newImgNumber
variable to a random integer between
0
and
3
:
function changeImg(that) {
var newImgNumber = Math.round(Math.random() * 3);
The
Math.random()
method provides a random number between
0
and
1
, and you multiply that by
three to get a number between
0
and
3
. This number is rounded to the nearest whole number (
0
,
1
,
2
,
or
3
) by means of
Math.round()
. This integer provides the index for the image
src
that you will select
from the
myImages
array.
The next lines are a
while
loop, the purpose of which is to ensure that you don't select the same
image as the current one. If the string contained in
myImages[newImgNumber]
is found inside the
src
property of the current image, you know it's the same and that you need to get another random
number. You keep looping until you get a new image, at which point
myImages[newImgNumber]
will
not be found in the existing
src
, and
‐1
will be returned by the
indexOf()
method, breaking out of
the loop:
while (that.src.indexOf(myImages[newImgNumber]) != -1) {
newImgNumber = Math.round(Math.random() * 3);
}
Next, you set the
src
property of the
img
object to the new value contained in your
myImages
array:
that.src = myImages[newImgNumber];
}
You connect the
onclick
event of the first
<img/>
element to the
changeImg()
function:
<img src="usa.gif" onclick="changeImg(this)" />
And now to the second
<img/>
element:
<img src="mexico.gif" onclick="changeImg(this)" />
Passing
this
in the
changeImg()
function gives the function direct access to this
<img/>
element's
corresponding object. When you pass
this
to an HTML element's attribute event handler, the
corresponding object of that element is passed to the function. It's a nice, clean way of accessing the
element's object in your JavaScript code.
This example had you pass
this
as an argument to the function handling the element's
click
event.
This is a simple and easy way of accessing the element that received the event, but there's a far more
useful object you can pass: an
Event
object that contains all the information about the event.
Passing the
Event
object is very simple to do; simply pass
event
instead of
this
. For example, in the
following code the
<p/>
element will raise a
dblclick
event:
<p ondblclick="handle(event)">Paragraph</p>
<script>