Skip to content Skip to sidebar Skip to footer

Onclick Event Is Triggered Without Clicking

This is a simple dice throwing event, 6 dice, generated by a random number, everything works, I'm getting the data in the console but I want it triggered only when clicking on the

Solution 1:

That's because you're assigning the result of executing rollDice(results) to your clickButton.onclick function. You're not telling it to execute that function when the element is clicked. To avoid this, wrap that in a function call itself:

clickButton.onclick = function() { rollDice(results); }

Now your click will execute that function which only then executes the rollDice function.


To expand on what's happening here. Let's say we have a function foo which returns the string "bar":

function foo() { return "bar"; }

If we're to assign foo() to a new variable, JavaScript will execute the foo function there and then and assign the result of that function to our new variable:

var baz = foo();
-> "bar"

However if we place our foo() function call within another function call, our original function will not be immediately executed:

var baz = function() { return foo(); }
-> function() { return foo(); }

If we now call baz(), it will execute its own function which itself executes our original foo function:

baz();
-> "bar"

The same applies with your onclick function. Rather than telling the onclick to execute our function when the element is clicked, we're assigning "bar" to our onclick function:

elem.onclick = foo();
-> "bar"

Post a Comment for "Onclick Event Is Triggered Without Clicking"