I'm trying to create a coin flip game, with a button for both guessing heads and tails with appropriate outputs for the guess - you guessed x, and the answer is x, you're correct/you guessed x and the answer is y, you're incorrect. I'm new to JS, and I'm struggling to find out why I'm not having results for the game when buttons are clicked.
document.getElementById('flipHeads').onclick = click;
var flipHeads = Math.round(Math.random()) + 1;
function click(flipHeads) {
if (coinFlip == 1) {
var Result = "flipHeads";
} else {
var Result = "flipTails";
}
if (Result == flipHeads) {
if (Result == "heads") {
alert("The flip was heads and you chose heads...you win!");
} else {
alert("The flip was tails and you chose heads...you lose!");
}
}
}
document.getElementById('flipTails').onclick = click;
function click(flipTails) {
var flipTails = Math.round(Math.random()) + 1;
if (Result == fliptails) {
alert("The flip was heads and you chose tails...you lose!");
} else {
alert("The flip was tails and you chose tails...you win!");
}
}
function flip(flipHeads) {
document.getElementById("result").innerHTML = Heads;
};
function flip(flipTails) {
document.getElementById("result").innerHTML = Tails;
};
<div>
<button id="flipHeads" type="button">Heads</button>
<button id="flipTails" type="button">Tails</button>
<div id="result"></div>
</div>
I simplified your code and made it actually work. I will go step by step through the changes:
div
and ID (flip). Then I changed the ID of the button to justHeads
orTails
.eventListener
that looks for a click event within thediv id="flip"
button
and not the containing element itself.Heads
orTails
Heads
orTails