1

When we have a predefined JS function:

function myFunction() { script }

Why when we call it during an event (for e.g onclick) from HTML, we use the parameter parentheses:

<button onclick="myFunction()">Sumbit</button>

while when we call it from JS, we use the function name without parentheses?:

document.getElementById("button").onclick = myFunction;
  • 1
    That's just how it is defined: to the `onclick` attribute you must provide an expression, while the `onclick` property needs a function reference. – trincot Mar 24 '18 at 18:38
  • `on` is a prefix that gets added to inline HTML event attributes to denote what JavaScript to execute when the event happens. The event is just `click`. It's also used on event properties in JavaScript. Both of these techniques are old and antiquated and should no longer be used. Instead, follow modern standards and use `.addEventListener()`. – Scott Marcus Mar 24 '18 at 18:55
  • https://stackoverflow.com/questions/43459890/javascript-function-doesnt-work-when-link-is-clicked/43459991#43459991 – Scott Marcus Mar 24 '18 at 18:56

2 Answers2

1

With onclick="myFunction()", JS runs the code inside "" as an expression, so why we call our function there. Means that when click is occurred call that function.

With .onclick = myFunction, we assign a reference of the function to the onclick property, which is called when the click is occurred. It may be called like something this

// Somewhere when the click is detected

if(triggeredClick) {
   this.onclick();
}

Here the function is called, via the onclick, which refers to the function.

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0

When we have a predefined JS function:

function myFunction() { script }

We call it during an event (for e.g onclick) from HTML, we use the parameter parentheses:

<button onclick="myFunction()">Sumbit</button>

Because:

  1. Above "myFunction" is loosely coupled with any HTML element
  2. Above "myFunction" can be called by multiple HTML elements
  3. Above "myFunction" can be called on different events (onClick, onChange etc.)

While when we call it from JS, we use the function name without parentheses:

document.getElementById("button").onclick = myFunction;

Because:

  1. Above "myFunction" is tightly coupled with any HTML element with Id "button"
  2. Above "myFunction" can ONLY be called by HTML element with Id "button"
  3. Above "myFunction" can ONLY be called by "onClick" event and no other
Abhishek
  • 41
  • 3