Like the title says, I want to have the buttons stop adding score and updating the player/cpu choices on the page. But I can't seem to figure out how to have that happen. Everything I've tried so far doesn't work and the buttons keep on adding score + changing the choices on the page.
I've tried Googling around to find a way to remove the event listener in my endGame() function. But I'm not sure if my syntax is wrong or if there is a different way entirely.
I tried using removeEventListener and I've tried disabling the buttons but that doesn't seem to work. I came across creating handlers to store reference to the function in question, but I have no idea how to apply it to my existing code. Here is my code as reference.
gameButtons.forEach(button => {
button.addEventListener("click", () => {
playerSelection = button.value;
playGame();
})
})
`
function compare(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
}
else if (playerSelection === "rock" && computerSelection === "scissors") {
playerScore++;
}
else if (playerSelection === "paper" && computerSelection === "rock") {
playerScore++;
}
else if (playerSelection == "scissors" && computerSelection === "paper") {
playerScore++;
}
else {
computerScore++;
}
playerScoreText = document.querySelector(".player-score").textContent = `Player score: ${playerScore}`;
computerScoreText = document.querySelector(".cpu-score").textContent = `CPU score: ${computerScore}`;
}
function getComputerChoice() {
return choice[Math.floor(Math.random() * choice.length)]
}`
function playGame() {
let playerChoice = document.querySelector(".player-choice").textContent = `Player Chose: ${playerSelection}`
let computerSelection = getComputerChoice();
let cpuChoice = document.querySelector(".cpu-choice").textContent = `Computer Chose: ${computerSelection}`
compare(playerSelection, computerSelection);
endGame();
}
function endGame() {
if (playerScore === maxScore) {
console.log("you won")
}
else if (computerScore === maxScore) {
console.log("you lost")
}
}````
.removeEventListener() needs to be given the same function instance (and the same original value of the
captureoption). Just assign your arrow function to a variable, and then use that variable to remove the listener later.