Search code examples
javascriptbuttondice

How do you create a button that works in javascript?


EDIT: So a few solutions work. Thing is, they work in codepen.io. But when I try to reload the actual HTML page from my computer to Chrome, the button clicks and shows nothing. Chrome is saying: 'dice.js:12 Uncaught TypeError: Cannot set property 'onclick' of null at dice.js:12.' How do I fix that?

I've looked at multiple similar questions that have different answers, and none of the answers I've tried has worked. I was able to make a random dice roll with the below code:

const min = 1;
const max = 7;

function diceRoll(random) {
    random = 0;
    while (random <= 0) {
        random = Math.floor(Math.random() * (max - min) + min);
        document.write('Dice # ' + random);
    }
}

My html is:

<button id="roll">Throw Dice</button>

I haven't learned how to make buttons work, or how to start the javascript (other than writing it in the console. Can anyone help with how to create a button to make it work so I don't have to use the console? See below for what I've tried:

let button = document.getElementById('roll');

button.onclick = function() {
    let result = diceRoll();
    printNumber(result);
};

Another try:

 document.getElementById("roll").onclick = diceRoll();

And another:

document.getElementById("roll").onclick = function() {
    diceRoll();
};

Solution

  • Try this

    <!DOCTYPE html>
    
    <html lang="en">
        <head>
            <script>
                const min = 1;
                const max = 7;
    
                function diceRoll(random) {
                    random = 0;
                    while (random <= 0) {
                        random = Math.floor(Math.random() * (max - min) + min);
                        document.write('Dice # ' + random);
                    }
                }
            </script>
        </head>
        <body>
            <form onsubmit='diceRoll()'>
                <button>Throw Dice</button>
            </form>
        </body>
    </html>