Head or Tails game code

Can anyone help me change the code below to make clicking either the Heads or Tails button perform the Math.random function to display the result “you win” or “you lose” in the paragraph tag. I am new to this and spent a lot of time to come up with this code but can’t make it quite work.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

<H1>Heads or Tails Game</H1>>

<button id="demo" >Heads</button>

<button id="demo1">Tails</button>

<p id="demo2">Heads or Tails</p>

    let n;  
    n = Math.floor(Math.random() * 10);
        if (n > 5) {
            document.getElementById("demo2").innerHTML = "you win";
        } else{
            document.getElementById("demo2").innerHTML = "you lose";



I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

HI @VlTs !

Welcome to the forum!

A big piece of the functionality for this is the button click.

If you google, javascript button click then you will get tons of articles on how to use this method.

My advice would be to wrap this logic into a function.

You can call the function whatever you want.

Then read through how to use button click events for javascript and reference that function in your button click.

Hope that helps!

1 Like

Here is a good freecodecamp article to look at

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.