David Caldwell David Caldwell - 1 month ago 12x
Javascript Question

JavaScript Dice Roll When Button Is Clicked

I am trying to make a simple dice roller with Javascript that will display a random number between 1 and 6 when the button is clicked.

I have a button:

<button id="roll">Click to Roll</button>

With this script:

function diceRoll(min, max) {
var min = Math.ceil(min);
var max = Math.floor(max);
var roll = Math.floor(Math.random() * (max - min + 1)) + min;

document.getElementById("roll").onclick = diceRoll(1, 6);

The random number will display when the page is first loaded, but when clicking the button nothing happens. How can I get this to work when the button is clicked, not when the page is loaded? Thank you.


Use this instead:

document.getElementById("roll").onclick = function() {
    diceRoll(1, 6);

The issue with your current code is that when that line is run, diceRoll(1, 6) is executed, and then the result of calling that function is assigned to the onclick handler.

You need the onclick handler to instead be a function that can be called each time the button is clicked. So above I've created a new function that, when called, in turn calls diceRoll(1, 6).

If it helps, this code is equivalent to what you're doing now (and hopefully reveals why that's wrong):

// Call diceRoll and store its result (which is undefined, since
// the function returns nothing).
var result = diceRoll(1, 6);

// Now take that result (undefined) and assign it to the button's
// onclick handler. This makes onclick undefined too.
document.getElementById("roll").onclick = result;