Why in JavaScript event handler functions with parentheses?

dom-events, javascript

Solution

Inline JS

When you do an inline onclick handler like that, you're assigning a Javascript expression to run. So you need to execute the function.

The expression could just as easily be `onclick="handler();alert(2)"` in which case its obvious that the function needs to be called, just like it would be if it were run from a javascript file.

Binding a function to the click event

If instead you attach the click event with javascript, you would be binding a function, so you just need to pass the function object.

var btn = document.getElementById("btn");
btn.addEventListener("click",handler);

`addEventListener` sets the function object to be bound to the event so that it executes when the event is triggered. Since you're specifying a function object, rather than a string expression, the parentheses are not needed. In fact if you added them the function would execute immediatelly and the return value of the function would be bound to the event.

Best Practice

In general most people would advocate you bind events in javascript by binding a function handler rather than using inline JS. Its easier to debug, doesn't tightly bind your logic to the DOM, and is more flexible for dynamic pages. It also forces you to make any functions that you're calling global.

Summary

The key is the attribute points to a string that is evaluated as a JS expression, it is not the same as binding a function object to the event.

Problem

Look at this code: ``` <button onclick="handler()">ClickMe</button> <script> function handler() { alert("clicked"); } </script> ``` Why `onclick` event should be assigned to handler with `()` `onclick="handler()"`? In this case alert is called. But according to the logic described as answer to similar question https://stackoverflow.com/a/3247044/2543590 `onclick` assigned to result of function handler, not to function itself. I believe to assign `onclick` to function it should be like this ``` onclick="handler", ``` but in this case alert is not called. Why?

Original source

Related problems