I'm working on a "Rock, Paper, Scissors" project. The user clicks one of three buttons (either rock, paper, or scissors), then the computer will choose, then the winner is displayed. Once the user selects which one they want to play, I want to be able to use the variable "userChoice" that has their choice later in the code.
This is my HTML for buttons:
<div class="buttons">
<button id="Rock">Rock</button>
<button id="Paper">Paper</button>
<button id="Scissors">Scissors</button>
</div>
This is my Javascript:
document.addEventListener('DOMContentLoaded', function(event) {
document.querySelector('#Rock').onclick=function(e){
const userChoice = "Rock";
}
document.querySelector('#Paper').onclick=function(e){
const userChoice = "Paper";
}
document.querySelector('#Scissors').onclick=function(e){
const userChoice = "Scissors";
}})
Try this approach. Now when the user clicks the Log user choice button you see what they have clicked.
let
userChoice = ''
document.querySelector('#Rock').onclick = function() {
userChoice = "Rock";
}
document.querySelector('#Paper').onclick = function() {
userChoice = "Paper";
}
document.querySelector('#Scissors').onclick = function() {
userChoice = "Scissors";
}
let
user_choice = document.querySelector('#user-choice')
user_choice.addEventListener('click', function() {
console.log(userChoice)
})
<div class="buttons">
<button id="Rock">Rock</button>
<button id="Paper">Paper</button>
<button id="Scissors">Scissors</button>
</div>
<p>
<button id="user-choice">Log user choice</button>
</p>