Reputation: 23
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";
}})
Upvotes: 1
Views: 1230
Reputation: 1
function computerChoice() {
let randomNumber = Math.round(Math.random() * 2)
const list = ["rock", "paper", "scissors"];
randomCoice = list[randomNumber];
return randomCoice;
};
let userChoice = '';
document.querySelector(".rock").onclick = function() {
userChoice = 'rock';
computer = computerChoice()
result();
// console.log(userChoice);
// console.log(computerChoice());
}
document.querySelector(".paper").onclick = function() {
userChoice = 'paper';
computer = computerChoice()
result();
// console.log(userChoice);
// console.log(computerChoice());
}
document.querySelector(".scissors").onclick = function() {
userChoice = 'scissors';
computer = computerChoice()
result();
// console.log(userChoice);
// console.log(computerChoice());
}
function result() {
if (userChoice === computer) {
alert(`You chose ${userChoice} and Computer chose ${computer}, its a Draw`);
} else if (userChoice === 'rock' && computer === 'paper'){
alert(`You chose ${userChoice} and Computer chose ${computer}, You Lose`);
} else if (userChoice === 'paper' && computer === 'scissors'){
alert(`You chose ${userChoice} and Computer chose ${computer}, You Lose`);
} else if (userChoice === 'scissors' && computer === 'rock'){
alert(`You chose ${userChoice} and Computer chose ${computer}, You Lose`);
} else{
alert (`You chose ${userChoice} and Computer chose ${computer}, You Win!!`);
}
}
Upvotes: 0
Reputation: 335
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>
Upvotes: 2