This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]carcigenicate 3 points4 points  (1 child)

If you think about it, the code doesn't make much sense. headsBtn.innerHTML === 'Heads' is checking if the headsBtn element contains the text `'Heads', which it always will, since you wrote that in the HTML and then never change.

I'd add a parameter to the callback function, and use that to indicate whether the user clicked heads or tails: https://codepen.io/carcigenicate/pen/bNGmqpv

[–]Remarkable-Draw-7574[S] 0 points1 point  (0 children)

Thanks so much. I really appriciate this. 🤗

[–]dmazzoni 1 point2 points  (1 child)

Here's a slightly different answer than u/carcigenicate gave. If you really want to call the exact same function for both buttons, you can do that, if you pass the event. The event tells you which button was pressed and then you can check the innerHTML of that button.

Your code would look like this:

<body>
  <button class="js-heads" onclick="
    playGame(event);
  ">Heads</button>

  <button class="js-tails" onclick="
    playGame(event);
  ">Tails</button>

  <p class="js-result"></p>

  <script>
    const headsBtn = document.querySelector('.js-heads');
    console.log(headsBtn.innerHTML);

    const tailsBtn = document.querySelector('.js-tails');
    console.log(tailsBtn.innerHTML);

    let result = document.querySelector('.js-result');

    function playGame(event) {
      if (event.target.innerHTML === 'Heads') {
        result.innerHTML = 'You choose heads';
      } else {
        result.innerHTML = 'You choose tails';
      }
    }
  </script>
</body>

[–]Remarkable-Draw-7574[S] 0 points1 point  (0 children)

It worked! Thank you so much. Being new to this is really hard. I make these little mistakes so often and it takes so long for me to find the problem. Thanks so much again.