4

I'm very new to HTML and JavaScript. I have seen onclick been assigned to function with following parentheses onclick="confirmOnSubmit() and functions without following parentheses onclick="confirmOnSubmit.

I was just wondering what is the difference between the two? When should I use one over the other?

<input type="submit" value="Submit" id="submitID" onclick="confirmOnSubmit()"/>
halfer
  • 19,471
  • 17
  • 87
  • 173
Thor
  • 9,110
  • 14
  • 56
  • 125
  • 2
    Where have you seen the latter? – Phil Jul 06 '16 at 04:09
  • for example, document.getElementById("buttonID2").onmouseover = changeColorOnMouseOver vs document.getElementById("buttonID2").onmouseover = changeColorOnMouseOver(); . where changeColorOnMouseOver is the name of a function – Thor Jul 06 '16 at 04:49
  • That's entirely different to your **HTML** examples of `onclick="confirmOnSubmit()"` vs `onclick="confirmOnSubmit"` – Phil Jul 06 '16 at 05:08

1 Answers1

6

using parentheses after a function name means invoking that function.However, using it without a parentheses just means the function itself.

<input type="submit" value="Submit" id="submitID" onclick="confirmOnSubmit()"/>

so in your example, it is basically saying that whenever the submit btn is clicked, invoke the confirmOnSubmit function.

<input type="submit" value="Submit" id="submitID"/>

document.getElementById('submitID').onclick=confirmOnSubmit 

however, in the above example, we don't want to call the function at that moment, we just want to assign a reference, so that it can be called later on when the event happens.

hope it helps.

Soheil
  • 612
  • 1
  • 8
  • 17