Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coin toss with JavaScript and HTML

I need help fixing my script. Basically, I want it to flip a coin and update a <span> with the result, i.e. if it's heads or tails. At the moment, nothing happens when I click the button.

JavaSript:

var heads = 0;
var tails = 0;
function click() {  
    x = (Math.floor(Math.random() * 2) == 0);
    if(x){
        flip("heads");
    }else{
        flip("tails");
    }
};
function flip(coin) {
    document.getElementById("result").innerHTML = coin;
};

HTML:

<button id="click" type="button">CLICK ME</button>
<p>
    You got: <span id="result"></span>
</p>
like image 442
klee Avatar asked Aug 30 '15 23:08

klee


People also ask

How do you flip a coin in Javascript?

coinFlip.jsvar n = Number(prompt("How many times do you want to flip the coin?")); // Gets the number of times to flip the coin. var heads = 0, tails = 0; // Initiates the heads and tails variables. // Uses the Math. random function to generate a random number.

Is there a coin toss app?

Flip a Coin app looks great on both your iPhone and your iPad! -Lands on heads or tails. It's a random coin flip just like in real life. -Choose different coins to flip!

What is the coin toss method?

The toss or flip of a coin to randomly assign a decision traditionally involves throwing a coin into the air and seeing which side lands facing up. This method may be used to resolve a dispute, see who goes first in a game or determine which type of treatment a patient receives in a clinical trial.


1 Answers

That's simply because you need to attach the event handler:

document.getElementById('click').onclick = click;

var heads = 0;
var tails = 0;
function click() {  
    x = (Math.floor(Math.random() * 2) == 0);
    if(x){
    	flip("heads");
    }else{
        flip("tails");
    }
};
function flip(coin) {
    document.getElementById("result").innerHTML = coin;
};
<button id="click" type="button">CLICK ME</button>
<p>
    You got: <span id="result"></span>
</p>
like image 161
Amit Avatar answered Oct 03 '22 20:10

Amit