-1

I want to define an onclick action, but it's executing it's self after this line:

document.getElementById("rollDiceAction").onclick = rollDiceSpecial();

What can I do?

Progaros
  • 45
  • 1
  • 12

2 Answers2

4

To reference a function, just say its name:

x = foo;  // Set x equal to the function foo

To invoke it put parenthesis after its name:

x = foo(); // Invoke foo and set x equal to the result

Just get rid of the parenthesis at the end of your line to associate the rollDiceSpecial function with the onclick property.

 document.getElementById("rollDiceAction").onclick = rollDiceSpecial;
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

Remove the parentheses:

document.getElementById("rollDiceAction").onclick = rollDiceSpecial;

You should really be using addEventListener, though -- assigning to the element's onclick attribute is a bit old-school, and limits you to one event handler per element.

document.getElementById("rollDiceAction").addEventListener("click", rollDiceSpecial);