Skip to content
Advertisement

Event Listener function not returning any value

I am lost and I would like to understand where is my error, or what should I check to figure it out.

I am building a simple Rock Scissors game. I can’t return any values from Event Listener function to a variable. Console.log returns undefined.

function listeningToPlayer () {
    const btn = document.querySelectorAll(".btn");
    btn.forEach(btn => btn.addEventListener ('click', (e) => {
    if(e.target.innerHTML == "Rock") {
        return "rock"
    } else if (e.target.innerHTML == "Paper"){
        return "paper";
    } else if (e.target.innerHTML == "Scissors") {
        return "scissors";
    }
}))
}
// Variables with computer and player choices
let computer_selection = computerPlay()
let player_selection = listeningToPlayer()


console.log(player_selection)

Thanks in advance. Also, if someone could tell me if my Event Listener is very bad, I would be grateful. “innerHTML” was the best way I could figure out.

If my coding is ridiculous, sorry for that – I have started few days ago!

Advertisement

Answer

An event listener is a function that gets executed when an event happens. In this case a click. You register what must happen when the click occurs. In this case you like to update the game state with the selected value.

A more standard way of setting data on a html element is using the data attribute. For example: <button data-choice="paper">Paper</button>.

HTML:

<button class="btn" data-choice="paper">Paper</button>
<button class="btn" data-choice="scissors">Scissors</button>
<button class="btn" data-choice="rock">Rock</button>

<pre id="output"></pre>

Js:

const randomChoice = () => (['paper', 'scissors', 'rock'][Math.floor(Math.random() * 3)]);

const gameState = {
  player: null,
  computer: randomChoice()
}

const out = document.querySelector('#output');
const btns = document.querySelectorAll(".btn");

out.innerHTML = JSON.stringify(gameState, null, 2)

for (const btn of btns) {
  btn.addEventListener('click', e => {
    gameState.player = e.target.dataset.choice;
    out.innerHTML = JSON.stringify(gameState, null, 2);
  });
}

https://jsfiddle.net/h0z5vf7y/2/

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement