Onclick Event Is Triggered Without Clicking
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"