Lesson 13: Dynamically Changing the SRC of an IMG Element

In this lesson you will create a game of Rock Paper Scissors (RPS). The rules are simple enough... rock beats scissors, scissors beats paper, and paper beats rock.

1. Start with these Project Files. After you dowload and unzip the folder, you should see the following files.

2. Open index.html in your favorite browser. You should see the players vs computer game screen for RPS.

3. Open index.html in your favorite text editor. Notice that there is a link to a stylesheet named rps.css and a javascript file named rps.js.

There is an init() function in the JavaScript file that runs when the page finishes loading.

There is a gameWindow div with a position of relative that holds three other elements (btnGo, playerPanel, and computerPanel) each with a position of absolute.

btnGo has been styled (see #btnGo in rps.css) but does not yet have an onclick attribute.

The playerPanel has a level 2 heading (h2), a large image (imgPlayer) to show the player's selection (which is initially just a question mark), and three buttons all with the same style (see .iconButton in the CSS). Also, not that there are three functions already in the JavaScript file that run when the corresponding button is clicked.

The computerPanel has similar elements. However, because the computer will be selecting rock, paper, or scissors when the GO button is pressed, the divs representing these choices will not behave as buttons (the user will not be able to click on them). Therefore, referring to these divs as labels instead of buttons, and naming them with an lbl prefix, is logical.

4. Open rps.js if you have not done so already. The global variables declared at the top will be used to select HTML elements that we want to manipulate. These variables are given a value in the init() function, after we are sure they have been loaded.

We will be using these variables soon. We already have some code inside the functions that are called from the HTML when the rock, paper, and scissors buttons are pressed.

5. Change the imgPlayer image when the buttons are clicked by setting a new value for the src of the element. Remember to specify the location of the images.

Now the image should change when any of the rock, paper, or scissors buttons are pressed.


Test Yourself!

1. If a variable named imgShape is set equal to an IMG element, how would you use JavaScript to set the image that appears in the element to circle.png?
imgShape.style.innerHTML = 'circle.png';
imgShape.innerHTML = 'circle.png';
imgShape.style.src = 'circle.png';
imgShape.src = 'circle.png';
2. Use innerHTML when using JavaScript to change the ________ of an element.
CSS
HTML Contents
Attributes
Position
3. Use style when using JavaScript to change the ________ of an element.
CSS
HTML Contents
Attributes
Position