Sergi Sergi - 3 months ago 25
HTML Question

Javascript - Rigged coin flip (heads first)

Really basic function, I have a button that simulates a coin flip, I want to always show "heads" first and then randomize after that first input, current code does not work and it randomizes from the first click.

HTML:

<button id = "riggedCoin" onclick = "riggedCoinFlip()"> Rigged Coin </button>

<h1 id ="h2"> Coin Flip </h1>


JS:

function riggedCoinFlip() {

document.getElementById("h2").innerHTML = ("Heads!");

var coinFace = Math.floor(Math.random() * 2);

if (coinFace === 0) {
var h1 = document.getElementById("h2").innerHTML = ("Heads!");
} else {
var h1 = document.getElementById("h2").innerHTML = ("Tails!");

}
}

Answer

At first, #h2 element already contains Coin Flip text. So, we can use this to check for the first time. We don't need another variable to check it.

I've simplified the solution for you. You can try:

function riggedCoinFlip() {
  var el = document.getElementById("h2");

  if (el.innerHTML === " Coin Flip ") {
    el.innerHTML = "Heads!";
  } else {
    el.innerHTML = (Math.floor(Math.random() * 2) === 0
      ? "Heads" : "Tails") +"!";
  }
}
<button id="riggedCoin" onclick="riggedCoinFlip()">Rigged Coin</button>
<h1 id="h2"> Coin Flip </h1>