Search code examples
javascripthtmlrandomcoin-flipping

Javascript Submit Button Random Coin Toss


Hopefully this is a quick fix. I have a coin toss generator that functions correctly (yay!) But I would like to be able to hit the flip button multiple times and run the function without having to reload and refresh the page.

var randomNumber = Math.floor(Math.random() * 2) + 1;

document.getElementById("flip").onclick = function(junction){
  if(randomNumber == 1){
    document.getElementById("response").innerHTML = "Heads!";
  } else {
    document.getElementById("response").innerHTML = "Tails!";
  }
}
<!DOCTYPE html>
<html>
<head>
    <title>Heads or Tails</title>
</head>
<body>
    <h1>Will it be heads or tails?</h1>
    <h3 id="response"></h3>
    <button id="flip" type="button">Let's Flip!</button>
</body>
<script src="app.js"></script>
</html>


Solution

  • Look at that code snippet, it works!

    function junction(){
      var randomNumber = Math.floor(Math.random() * 2) + 1;
      
      if(randomNumber == 1){
        document.getElementById("response").innerHTML = "Heads!";
      } else {
        document.getElementById("response").innerHTML = "Tails!";
      }
    }
    <!DOCTYPE html>
    <html>
    <head>
    
        <title>Guess the Number!</title>
    </head>
    <body>
        <h1>Guess the Number!</h1>
        <p>See if you can guess the number between 1 and 50</p>
        <label for="guess"> Enter Your Guess </label>
        <input type="text" id="guess"><br>
        <button id="submit" onclick="junction();">Submit Guess</button>
        <p id="response"></p>
    </body>
    </html>