Categories
JavaScript Web development

Heads or Tails? Toss a Coin!

Learn how to toss a coin with HTML, CSS and JavaScript.



Toss a Coin JavaScript

Demo:

*to see the Coin Toss animation on the website 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 and follow the steps below:

  1. Add HTML
  2. Add CSS
  3. Add CSS Animation
  4. Add JavaScript
flip a coin
coin toss

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: rotateX(0deg);
    
  }
  50% {
    transform: rotateX(3600deg);
    
  }
  100% {
    transform: rotateX(7200deg);
    
  }
}

Step4.

Add JavaScript

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

function coinToss() {
  let x = Math.floor(Math.random() * 2);
  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();
}

Watch also the video tutorial:

Enjoy coding!

Hey, here’s something that might interest you:

Roll the dice!

CSS & JavaScript Memory Game

Games