Changing images with buttons
This program shows how to change an HTML image with a push button.
Programming Issues
Because we are using three images here (three national flags), we begin by setting up a status variable, n
,
to keep track of what the current image is. We initialise this to 0
. Note that this is declared outside
of the function. A variable declared inside a function has function scope; this means that the variable
is created anew each time the function is called, and destroyed when the function completes. If our n
variable
had function scope, it would not "remember" its value between function calls. By declaring it outside of any
function, we give the variable global scope, and it "remembers" its value between function calls.
This time, clicking the button calls the changeImage()
function via the onclick
event
handler. The function tests the value of n
to determine what action to take. If n
is equal to
0
(note we use the &&
operator to test for equality, as explained in our
previous example), which it is when the HTML document is first loaded, then the image
shown is the Welsh flag. In this case, we change the source of the image to the Scottish flag using the code:
document.images["flag"].src = "scotflag.png";
. As with our previous
example, we have given our image the id
"flag", because the name
attribute is also
deprecated for the <img>
tag in XHTML. Having changed the image, we update n
with the value
1
, so the next time the function is called we can "remember" what the current image is.
In an identical way, if n
is equal to 1
, then the image is changed to the Scottish flag, and
the value of n
updated to 2
. If n
is equal to anything else than 0
or
1
(in this case, the only other thing it can be equal to is 2
) then the image is changed back
to the Welsh flag, and n
reset to 0
. In this way, we can cycle endlessly through the Welsh,
Scottish and English flags, in that order, by successive clicks on the image.
Also note that, unlike previous example, we enclose the statements following if if
and else
statement in curly braces. If we want multiple statements to execute conditionally, we must enclose
the entire statement block in curly braces. If we do not do this, the first statement following the if
statement
will be executed conditionally, but the second and subsequent statements will be executed unconditionally.
Also note that we have introduced the else if
construct, since we are dealing with three possibilities, not
just two. This allows us to test for a number of possibilities, the else
block only being executed if
none of the previous conditions are met. If the condition in the first if
is evaluated as false, the script
moves on to the next else if
statement and evaluates that. It keeps testing subsequent else if
conditions until it either finds one that evaluates to true
, or until the else if
statements
come to an end.