skip to Main Content

I am trying to store the text of a button in a variable or function that i can use later. So it should be in the global scope i suppose. But i can’t figure out how to do that because if I console.log the function it shows undefined. I’m supposing it’s because the main function doesn’t actually return anything, the nested one does. I was thinking about giving names to the nested functions but i can’t figure out how to name these forEach and eventListener functions or if that would even help me. I am so lost. Please send help

function choice() {
  document.querySelectorAll('.container').forEach((button) => {
    button.addEventListener('click', (event) => {
      let playerChoice = event.target.textContent;
      return playerChoice;
    });
  });
}
console.log(choice());
<div class="container">
  <button class="rock">rock</button>
  <button class="paper">paper</button>
  <button class="scissors">scissors</button>
</div>

If instead i console.log the playerChoice and then i call the function it works but from what i know i can’t store that result.

2

Answers


  1. You can store the value in a global variable. But it won’t be available to log until after the user clicks, so you need another event listener to show that.

    let playerChoice;
    
    function choice() {
      document.querySelectorAll('.container').forEach((button) => {
        button.addEventListener('click', (event) => {
          playerChoice = event.target.textContent;
        });
      });
    }
    
    choice();
    document.querySelector("#show").addEventListener('click', () => console.log(playerChoice));
    <div class="container">
      <button class="rock">rock</button>
      <button class="paper">paper</button>
      <button class="scissors">scissors</button>
    </div>
    
    <button id="show">What did I click?</button>
    Login or Signup to reply.
  2. If you want to keep it in global variable, then declare the variable and set the value while you are clicking it. I have also gave you another function, getPlayerChoice as optional if you want to call any function to do certain things you can do in that way –

    var playerChoice;
    
    function getPlayerChoice(text) {
        console.log("text", text);
        console.log("global value", playerChoice);
        // You can do your work here
    }
    
    function choice() {
        document.querySelectorAll('.container').forEach((button) => {
            button.addEventListener('click', (event) => {
                playerChoice = event.target.textContent;
                getPlayerChoice(playerChoice);
            });
        });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search