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>
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.
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!
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With