Step 11
We are done with the design and styling of our application! It's time to implement the game. Let's create a script.js
file and link it to the index.html
by adding the following script
element to the bottom of the body
element, right above the </body>
tag:
<script src="script.js"></script>
Moreover, add event handler to the three buttons, and while at it, also add id
attributes to some of the elements so we can easily access them in script.js
:
<div class="container my-5">
<div class="row gap-2">
<div class="col-sm">
- <button class="btn btn-primary btn-lg w-100">Rock</button>
+ <button id="rock" onclick="play(event)" class="btn btn-primary btn-lg w-100">Rock</button>
</div>
<div class="col-sm">
- <button class="btn btn-primary btn-lg w-100">Paper</button>
+ <button id="paper" onclick="play(event)" class="btn btn-primary btn-lg w-100">Paper</button>
</div>
<div class="col-sm">
- <button class="btn btn-primary btn-lg w-100">Scissors</button>
+ <button id="scissors" onclick="play(event)" class="btn btn-primary btn-lg w-100">Scissors</button>
</div>
</div>
</div>
<div class="container">
<div class="card">
<div class="card-body">
- <h5 class="card-title">Draw!</h5>
+ <h5 id="result" class="card-title">Draw!</h5>
- <div>You selected scissors!<br/>The computer chose scissors!</div>
+ <div id="message">You selected scissors!<br/>The computer chose scissors!</div>
</div>
</div>
</div>
Notice the onclick
event handler is a function call play(event)
. Let's add it to the script.js
:
function play (event) {
const userChoice = event.target.id;
console.log(userChoice);
}
The play
function receives an event
object. The event object is a built-in Web API that contains many properties about the specified event, including a reference to the target element (target
) which the event occurred.
Let's run and test the application: