I’m re-doing a simple Rock, Paper, Scissors game this time adding an UI with DOM methods. I have a function getComputerChoice()
that works and returns a lowercase string with one of the three options randomly.
I have another function PlayRound(computerChoice, userChoice)
that takes both strings returned and does some comparisons over them.
function playRound(computerChoice, userChoice) {
if (userChoice === computerChoice) {
console.log("----------------");
console.log("Draw!");
console.log("User choice was: " + userChoice);
console.log("Computer choice was: " + computerChoice);
console.log("----------------");
inally I have a getUserChoice()
function that I’m updating. It used to look like:
function getUserChoice() {
let userChoice = prompt("What is your weapon? ");
return userChoice.toLowerCase();
}
And the program worked with that.
Now, instead of a prompt the user can click one of three buttons. I changed the button so that I get the id of each button which matches one of either three choices
//USER CHOICE METHOD
function getUserChoice() {
const userChoice = document.querySelectorAll('button');
userChoice.forEach((choice) => {
choice.addEventListener('click', () => {
console.log(choice.id);
})
})
}
The thing is that with this function “as-is” the playRound()
's userChoice
is undefined
, and in:
function getUserChoice() {
const userChoice = document.querySelectorAll('button');
userChoice.forEach((choice) => {
choice.addEventListener('click', () => {
console.log("this: " + this.id);
console.log(choice.id);
})
})
}
’ this
is undefined.
My question is, how do I make getUserChoice
(using the .forEach
and eventListener
) return a valid argument (string) that can be used by 'playRound()`?
I’ve been told that this
isn’t passed into arrow functions and that I should use an event parameter to a callback function along with event.target
. I don’t understand how. I’ve also been told that I shouldn’t use a callback function, or at least playRound()
as a callback function given that:
You are passing whatever playRound() returned to the addEventListener to call. That doesn't work since playRound() function does not return a function``