1 year ago
#389037
Eric Petela
Store addEventListener in variable in JS
I am making a rock, paper, scissors game and I am trying to store some text in a variable when a click event takes place using addEventListener (when a user clicks a button to select either 'rock', 'paper', or 'scissors) but when I console.log the variable I get 'undefined'. I have a return statement in there and if I console.log within the arrow function and click the button I get the right result but outside I am getting undefined. Here is the code I have
let playerRock = document.querySelector('#rock');
let rockChoice = playerRock.addEventListener('click', (e) => {
let choice = e.target.innerText
console.log(choice) // returns "Rock"
return choice
});
console.log(rockChoice) // returns "undefined"
I have another function that grabs the text from the button when I click it and then puts it on the screen so I know e.target.innerText works to some extent. Here is that code:
function getAndDisplayText(e) {
let choice = e.target.innerText
displayPlayerChoice.textContent = choice;
let computerChoice = computerPlay()
displayComputerChoice.textContent = computerChoice
versus.textContent = "vs:"
}
playerRock.addEventListener('click', getAndDisplayText)
Any help or insight is much appreciated
javascript
variables
addeventlistener
0 Answers
Your Answer