0

I'm making a rock, paper, scissors game with plain JavaScript. I have three divs with choices for rock, paper, or scissors, which the user can click. I have another empty div which I would like to update with the text of the div the user clicks on ('rock', 'paper', or 'scissors'). However, the text shows up as 'undefined' each time. My code is below. Any ideas what I'm doing wrong?

const yourChoice = document.querySelector('#your-choice');

function userChoice() {
  yourChoice.innerHTML = this.innerHTML;
}
<div id="your-choice-container">
  <div id="your-choice"></div>
</div>

<div id="choice-container">
  <div class="choice" id="rock" onclick="userChoice()">Rock</div>
  <div class="choice" id="paper" onclick="userChoice()">Paper</div>
  <div class="choice" id="scissors" onclick="userChoice()">Scissors</div>
</div>
Matthew Russo
  • 61
  • 2
  • 5

3 Answers3

1

You need to pass the object you are referencing as a parameter. Calling this on the function calls the scope of the function. not the object

const yourChoice = document.querySelector('#your-choice');

function userChoice(obj) {
  yourChoice.innerHTML = obj.innerHTML;
}
<div id="your-choice-container">
  <div id="your-choice"></div>
</div>

<div id="choice-container">
  <div class="choice" id="rock" onclick="userChoice(this)">Rock</div>
  <div class="choice" id="paper" onclick="userChoice(this)">Paper</div>
  <div class="choice" id="scissors" onclick="userChoice(this)">Scissors</div>
</div>
1

When called without context, and outside of strict mode, this inside of a function will be window, and window.innerHTML is undefined, because there's no such global variable.

In general, you should not use the event attributes (like onclick), but instead take a look at .addEventListener()

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
0

The problem seems to be with "this". One way is to pass in an argument in the function like below.

Here are some more solutions

const yourChoice = document.querySelector('#your-choice');

function userChoice(chosen) {
  yourChoice.innerHTML = chosen;
}
<div id="your-choice-container">
  <div id="your-choice"></div>
</div>

<div id="choice-container">
  <div class="choice" id="rock" onclick="userChoice('Rock')">Rock</div>
  <div class="choice" id="paper" onclick="userChoice('Paper')">Paper</div>
  <div class="choice" id="scissors" onclick="userChoice('Scissors')">Scissors</div>
</div>
Sujil Maharjan
  • 1,307
  • 10
  • 12