Wait for a button click before proceeding

3.3k views Asked by At

I have an alert pop up asking "would you like to play" and if the answer is true it runs some code. But after you click "yes" I wish for a button to be pressed, and my code continues to run without waiting for it to be pressed.

Here is what I have as Javascript:

var start = confirm("Would you like to Play?");
var plays = 0;
var playerScore = 0;
var computerScore = 0;
var userChoice = ""
function choose(buttonChoice) {
    userChoice = buttonChoice;
}

while(start) {

    var pScoreDiv = document.getElementById('pScore');
    pScoreDiv.innerHTML  = playerScore;

    var cScoreDiv = document.getElementById('cScore');
    cScoreDiv.innerHTML  = computerScore;

    console.log(playerScore);
    console.log(computerScore);

    var computerChoice = Math.random();

    if (computerChoice < 0.34) {
        computerChoice = "rock";
    } else if(computerChoice <= 0.67) {
        computerChoice = "paper";
    } else {
        computerChoice = "scissors";
    }
}
<button onClick="choose('rock')">Rock</button>
<button onClick="choose('paper')">Paper</button>
<button onClick="choose('scissors')">Scissors</button>

2

There are 2 answers

0
Richard Parnaby-King On BEST ANSWER

You are only listening for the confirm button to be chosen, not the buttons to be clicked on.

In the below code I have changed the while into a function that checks if start has been set, and is called when a button is clicked on.

var start = confirm("Would you like to Play?");
var plays = 0;
var playerScore = 0;
var computerScore = 0;
var userChoice = ""

function choose(buttonChoice) {
  userChoice = buttonChoice;
  play();
}

function play() {
  if (start) {
    var pScoreDiv = document.getElementById('pScore');
    pScoreDiv.innerHTML = playerScore;

    var cScoreDiv = document.getElementById('cScore');
    cScoreDiv.innerHTML = computerScore;

    console.log(playerScore);
    console.log(computerScore);

    var computerChoice = Math.random();

    if (computerChoice < 0.34) {
      computerChoice = "rock";
    } else if (computerChoice <= 0.67) {
      computerChoice = "paper";
    } else {
      computerChoice = "scissors";
    }
  }
}
<button onClick="choose('rock')">Rock</button>
<button onClick="choose('paper')">Paper</button>
<button onClick="choose('scissors')">Scissors</button>

0
Oscar Bout On

Try

if (start == true) {

instead of

while (start) {