onclick="" vs event handler

Viewed 23192

If I want a function to be executed, I prefer doing inline js:

<p id="element" onclick="doSomething();">Click me</p>

because it is easier to debug.

However, I hear people saying not to use inline js, and do:

document.getElementById('element').onclick = doSomething;

Why is the js event listener recommended?

9 Answers

I see some saying there needs to be a separation of concerns regarding Presentation and Business Logic.

OP in his example does indeed show this separation! There is no logic in the inline event handler, but merely a function reference/call that will get executed on the "click" event... the logic itself can be separately maintained elsewhere.

I personally prefer this approach due to logical flow discoverability. If I have never seen an application before... the first place I'm going to begin my code traversal is in the DOM, and right there it will be clear which event handlers are in play and which functions are providing the logic to the handlers. With using, say a "JQuery.On" eventing approach, by just glancing through the html you would have no idea which handlers are actually wired up and providing functionality.

Inline event handlers that simply provide pointers to functions is simply wiring up the events and not leaking logic into presentation.

I'm surprised that nobody has mentioned content security policy (CSP) as a reason to use event properties in place of event attributes. I think that trumps any of the personal preferences given so far.

When properly implemented (i.e. not adding "unsafe-inline", which is utter nonsense imho) CSP1.0 basically blocks all forms of inline script. Making inline event attributes impossible. While CSP2.0 attempts to remedy this by providing a "nonce" for inline script, it does not provide such a thing for inline event attributes. CSP3.0 adds "unsafe-hashes" for inline events, but still no sign of a nonce.

So, in the absence of a nonce for inline events, event properties (or event listeners) is very much the way to go from a CSP standpoint.

Related