Categories
JavaScript Web development

Heads or Tails? Coin Flip JS

Heads or tails? Can’t decide? 🙂

Coin tossing JS

Flip coin with JavaScript!

*animation opened in the Safari browser.
To see the live output click here.

What do you need to do?

To create coin flip animation you will need two images of the coin (front and back) in .png format (to practise you can use these below) and follow the steps below:

  1. Add HTML
  2. Add CSS
  3. Add CSS Animation
  4. Add JavaScript

Step1.

Add HTML

<div id="coin"></div>
<div id="button">Toss a coin</div>

Step2.

Add CSS

body {
  background-color: #457b9d; 
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;  
}

#coin {
   position: relative;
}

#button {
  background-color:#e9c46a;
  color:#fff;
  padding:15px 15px;
  border-radius:30px;
  display:inline-block;
  transition:0.5s;
  cursor:pointer;
}

#button:hover {
    opacity:0.5;
    background-color: #ef233c;
  }

Step3.

Add CSS Animation

.animate-coin {
  animation: flip 2s 1;
}

@keyframes flip {
  0% {
    transform: scale3d(1,1,1) rotateX(0deg);
    
  }
  50% {
    transform: scale3d(1,1,1) rotateX(3600deg);
    
  }
  100% {
    transform: scale3d(1,1,1) rotateX(7200deg);
    
  }
}

Step4.

Add JavaScript

var coin = document.getElementById("coin");
var button = document.getElementById("button");
var heads = 0;
var tails = 0;

/* On click of button spin coin ainamtion */
function coinToss() {
  /* Random number 0 or 1  */
  var x = Math.floor(Math.random() * 2);
  /* If statement */
  if (x === 0) {
    coin.innerHTML = '<img class="heads animate-coin" src="https://lenadesign.org/wp-content/uploads/2020/06/head.png?w=100"/>';   
    heads += 1;
   
  } else {
    coin.innerHTML = '<img class="tails animate-coin" src="https://lenadesign.org/wp-content/uploads/2020/06/tail.png?w=100"/>';
     tails += 1;
  }
}

button.onclick = function() {
  coinToss();
}

To see the live output of the animation go to lenastanley.com.

Enjoy coding!