Learn to Code via Tutorials on Repl.it

← Back to all posts
Coin Flipper with Sound using HTML and JavaScript
h
Aloeb83 (40)

This tutorial will teach you how to make a very simple Coin Flipper using HTML and Javascript. This program is so simple to make, it can be completed in around 5-10 minutes at most.

The first obvious step is to open a HTML/CSS/JavaScript Repl. Doing so will mean that about 90% or more of the HTML is already done for us, meaning we only have to add two simple lines inside the body of the HTML file to add a couple of buttons.

Before we do that, however, we want all needed files and folders to be in the right place. Now, again, the Repl will really already have this done for us, but personally I like to put the CSS and JavaScript file into a static folder, as that is how I was taught, though you shouldn't need it. If you choose to do this, simply add a folder called "static", move the CSS and JavaScript files into that folder and then make sure that the paths to both files is correct by adding "static/" before style.css in the href on line 7, as well as before script.js in the src of line 12.

We also want to add a "sounds" folder to our Repl making sure it's in our static folder if we have one created.

With that out of the way, let's get to the coding. We'll start with the HTML as it is by far the simplest.

For the HTML, we simply need to add two button tags inside the body tag. One will flip the coin, while the other will remove the coin image, so we can flip it again. The code will look like this:

<button id='coin-flip'>Flip Coin</button>
<button id='reset'>Reset</button>

It is important that each button has a unique id so that we can link these buttons to our JavaScript. Besides that, that's it for our HTML. We just need to add the JavaScript logic, so let's do that.

We'll first add this line of code:

let coinFlipper = {
    'coinSide': ['H', 'T'],
}

This will allow the computer to pick whether the coin lands on heads or tails and will randomize it a little later on. For now, we want to add the sound next. Before we can do that, we need to get a sound file. I found a simple file called coinfilp.mp3, downloaded it, and dragged the file into the sounds folder on my Repl. We can now use a "let" function to "create" a new Audio variable and associate the sound file with it so we can use it later in the Flip Coin button's function.

let coinFlipSound = new Audio('static/sounds/coinflip.mp3')

Next we add two Event Listeners, so that the proper functions take place when we click either button. For this program, I named the functions "coinFlip" and "reset."

document.querySelector('#coin-flip').addEventListener('click', coinFlip);
document.querySelector('#reset').addEventListener('click', reset);

We now can create the two functions for our buttons, as well as one we'll need to make the result random.

First, the reset function. It's very simple and only serves one purpose, removing the coin image so that our screen doesn't become flooded with them if we flip the coin multiple times. This function is still tied to a button, remember, so we will have to click it before we flip a second time.

function reset() {
    document.querySelector('img').remove();
}

All this line of code does is look for an Image and removes the image it finds if it finds one.

The next function we'll create is the one that will randomize the result. It'll end up looking like this.

function randomCoin() {
    let randomIndex = Math.floor(Math.random() * 2);
    return coinFlipper['coinSide'][randomIndex];
}

That first line allows the computer of either 0 and 1. We do this because arrays are indexed starting with the value of 0 for the first item, and then 1 for the second, and so on. By using Math.floor, we also make it so that the number is not a decimal and Math.random is how it picks the result. We then make sure that the value it chose is returned to us when we run the function later.

Last but not least, the actual coin flip function. I'm going to go over the function line by line, as it is the longest one. It looks like this:

function coinFlip() {
   coinFlipSound.play();

   let coin = randomCoin();
   let coinImage = document.createElement('img');

   if (coin === 'H') {
       coinImage.src = 'https://random-ize.com/coin-flip/us-half-dollar/us-half-dollar-front.jpg'
       setTimeout(function() { document.querySelector('body').appendChild(coinImage); }, 1000);
    
   }else if (coin === 'T') {
       coinImage.src = 'https://random-ize.com/coin-flip/us-half-dollar/us-half-dollar-back.jpg'
       setTimeout(function() { document.querySelector('body').appendChild(coinImage); }, 1000);
   }
}

The first line simply plays back the audio we set earlier regardless of what the result is. The next line allows us to set our random function as a variable to use in an if statement, while the third allows us to add an image tag to our HTML when the button is clicked.

Next is our if statement. It simply tells the computer that if our random result equals "H" or heads, to set the image source to a picture of a coin with heads side facing up. The images I used we're simply found online, with the image address used so that the computer can locate the image. If the result isn't heads, however, the else if statement kicks in and posts a picture of the tails side instead.

To actually post the image, we are using this line of code, to tell the computer to put the image inside the body tag.

document.querySelector('body').appendChild(coinImage);

However, instead of posting just that line, you'll see it's inside of a setTimeout function. This allows us to prevent the picture from showing up, until the time we want it to show up (in milliseconds). The time of the audio clip is about a second, so having it wait 1000 ms does the trick for us.

And that's it!

You could of course do more with this, like using CSS to style the buttons, make the image a certain size, or add a background. However, we were able to make this program with only two lines of HTML that we wrote ourselves, three JavaScript functions, and only five additional lines outside the functions themselves.

Thank you so much for reading this tutorial, I hope you enjoyed it. If you have any sort of feedback on it, please leave it in the comments, I'd love to hear it.

-Aloeb83

Commentshotnewtop
John_WardWard (142)

@Aloeb83 Always good to have cool new innovative tutorials!

2IsAPrimeNumber (10)

I flipped the coin and got 6 heads in a row. The chances of that are 1.5625%.

timmy_i_chen (940)

Thanks for sharing! By the way, if you add html after the triple backticks for code blocks, it will highlight the syntax for you :)

Aloeb83 (40)

@timmy_i_chen Thank you for reading my tutorial, and thanks for that info. I had been just indenting each line of code, but what you suggested seems much easier. I updated my post and it looks so much better now, so again thank you.