I would like the button I created to simply document "Heads" or "Tails" based off my function.
<button id="coinFlipper">Flip a Coin</button>
<script>
const coinFlip = function() {
let randomNumber = Math.random()
if (randomNumber < 0.5) {
document.write("Heads")
} else {
document.write("Tails")
}
}
</scipt>
CodePudding user response:
So First you need to create another element where you would display your result, than you need to create a function and assing this function on to a button with the onclick event like so -> if you want to change the text in the button just change the id of the button
const coin =()=>{
let randomNumber = Math.random();
if (randomNumber < 0.5) {
document.getElementById("result").innerHTML = "Heads";
} else {
document.getElementById("result").innerHTML = "Tails";
}
}
<button onclick="coin()" >Flip a Coin</button>
<p id="result"></p>