Im making a simple rock paper scissors game with html and js. I have got the computer to randomly choose one of the three options, but now I'm having issues with getting the users input by extracting the text content straight from the button. I know that I can get the value by having an event listener for all three button separately but just thought that it would be much better if I could have one event listener for all three.
Right now I am able to read the text content of the first button which is rock, but i'm not sure how to go about doing the same for the others on click.
My code so far:
let optionsArray = ["rock", "paper", "scissors"];
const getComputerChoice = () => {
let randomNumber = Math.floor(Math.random() * optionsArray.length);
return optionsArray[randomNumber];
};
const getPlayerChoice = () => {
const choice = document.querySelector("button");
let playerChoice = choice.textContent;
console.log(playerChoice);
};
getPlayerChoice();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>ROCK PAPER SCISSORS</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="" />
</head>
<body>
<button>rock</button>
<button>paper</button>
<button>scissors</button>
<script src="script.js" async defer></script>
</body>
</html>
Any help would be greatly appreciated.
CodePudding user response:
You'll need one or more event listeners, which can either be on each button or on a parent element. You can use event.target.closest("button")
to determine which button was clicked using event delegation.
const rpsOptions = ["rock", "paper", "scissors"];
const computerChoice = () =>
rpsOptions[~~(Math.random()*rpsOptions.length)];
const optionsEl = document.querySelector(".rps-options");
optionsEl.addEventListener("click", event => {
const btn = event.target.closest("button");
if (!btn || !optionsEl.contains(btn)) {
return;
}
console.log(
`you chose ${btn.textContent}, `
`computer chose ${computerChoice()}`
);
});
<div >
<button>rock</button>
<button>paper</button>
<button>scissors</button>
</div>