Jack Nilan         Javascript Tutorial        EMail : jacknilan@yahoo.com

Lesson 9 - Click a Button and Change Picture

In this project you are going to click a button and then the picture will change to the next picture. We are going to do this by putting our pictures into an array in the head and put a showpicture() function.

In the HEAD once again we have to put our arrays.

pictures = new Array (3);
pictures[0] = new Image;
pictures[0].src = "picture1.jpg";
pictures[1] = new Image;
pictures[1].src = "picture2.jpg";
pictures[2] = new Image;
pictures[2].src = "picture3.jpg";

var index = 0;

Once again we will use a function to show the picture but we must take out the call to setTimeout since we are now not looping.

The function will only have

function showpicture()
document.sample.src = pictures[index].src;
if (index == 3)
index = 0;

In our main program we will have

<img src = "picture1.jpg" name = "sample" height = 100>

<input type = "button" value = "Change Picture" onClick = "showpicture();">

The above line shows how we create a button. The value is the word that appears on the button. When the button is clicked we go to

function showpicture()