22

Is inline event handlers considered a bad practice?

For example: <button onclick=someFunction()>Click me!</button>

If so, what are the disadvantages of using inline event handlers?

Tibrogargan
  • 4,508
  • 3
  • 19
  • 38
haxxerz
  • 893
  • 6
  • 17
  • Does this answer your question? [Why is using onClick() in HTML a bad practice?](https://stackoverflow.com/questions/5871640/why-is-using-onclick-in-html-a-bad-practice) – Ivar Nov 18 '19 at 12:03

3 Answers3

32

It's a bad idea because...

  1. Best practice suggests a clear split between content, style and script. Muddying your HTML with inline JavaScript (or CSS) is not consistent with this.

  2. You can bind only one event of each kind (per element) with on*-style events , so you can't have two onclick event handlers, for example.

  3. If an event is specified inline, the JS is specified as a string (attribute values are always strings) and evaluated when the event fires. Evaluation is evil.

  4. Functions denoted by inline event handlers must be global (or at least globally accessible), which is rarely the case these days; code is normally namespaced, or encapsulated in modules (thanks, @Sebastian Simon).

  5. Any content security policy (CSP) you're using would have to be (unwisely) expanded to allow evaluated inline JavaScript.

In short, handle events centrally via the dedicated addEventListener API, or via jQuery or something.

[2021 Edit]

These days, reactive frameworks have somewhat reversed this trend; events in reactive frameworks are normally specified as attributes e.g. in Vue:

<p v-on:click='foo'>Hello</p>

...where foo is a method of the current component's data object.

HOWEVER, this is not true inline event handling; see @colin's comment under @adnanmuttaleb's answer.

Mitya
  • 33,629
  • 9
  • 60
  • 107
  • 1
    Here’s [another good list](https://stackoverflow.com/a/43459991/4642212) why `onclick` and such should be avoided. – Sebastian Simon Apr 26 '18 at 19:02
  • Also regarding point No.1 this can be solved, by using something like this `onClick="handler1() || handler2()....|| handlern()"` https://jsfiddle.net/ageck0bh/. – adnanmuttaleb Jun 25 '20 at 06:53
  • 3
    `v-on:click` isn't really an attribute. It's a directive, and under the hood it will be using `addEventListener` https://vuejs.org/v2/guide/events.html#Listening-to-Events – Colin Oct 10 '21 at 15:49
  • 1
    Really old post, but I've done a lot of research myself on this question. With the last part about React or Angular, etc. it's important to note the distinction. These frameworks use templating engines and what seems like inline JS is not in-fact. They'll be passed through a compiler or templating engines that will output the code as proper event listeners on those elements. Raw HTML has no such benefit. – HyperTextCoffeePot Oct 20 '22 at 03:36
  • 2
    Regarding point 4: Current best practices include using ECMAScript modules. Modules have their own module scope, which isn’t global scope. Since `on*` attributes rely on global scope, you’d have to set the function as a global property, defeating part of the purpose of modules, specifically the benefit of encapsulation. – Sebastian Simon Nov 01 '22 at 08:00
7

Aside from semantics and other opinions expressed in the accepted answer, all inline scripts are considered a vulnerability and high security risk. Any website expecting to run on modern browsers are expected to set the 'Content-Security-Policy' (CSP) property, either via meta attribute or headers.

Doing so is incompatible with all inline script and styles unless explicitly allowing these as an exclusion. While CSP goals are mainly about preventing persistent cross-site script (xss) threats, for which inline scripts and styles are a vector of xss, it is not default behaviour currently in browsers but may change in future.

Stof
  • 610
  • 7
  • 16
  • I suppose you mean no javascript at all in the HTML. But since you use the term inline javascript, i'd note that according to the highest voted answer here https://stackoverflow.com/questions/19618571/what-is-inline-javascript inline javascript is only the between the script tags.. it's not what's in eg an onclick., that'd be an inline event handler. – barlop Jul 27 '19 at 00:11
  • 2
    at the risk of repeating myself, you're pointing out that an onclick is an inline event handler is semantics, or distinction without a difference. A "handler" is scripting, ergo inline script. The "highest voted" is only highest due to bias, SO has extreme bias to developers, not security professionals. Were there more like myself on SO there'd be a more even representation of security minded people voting. Having fewer votes does not make the answer wrong, and beside SO only allows 1 accepted/right answer but you'd be inexperienced to consider questions have 1 right answer in reality. – Stof Jul 28 '19 at 02:35
  • @barlop Inline event handlers are considered inline JS by a CSP: It will block them unless you specify `'unsafe-inline'` or `'unsafe-hashes'` in `script-src`. – CheddarLizzard Jul 11 '23 at 07:14
  • the primary point is best described as, you want to let one molecule of water through the damn, but not the whole river... sure you can open the flood a little to get it through but you have no way to control that only that one thing is going to get through. Allowing inline scripts, even using a hash or nonce, without knowing what the code does, is just bad security. Do you know it won't pull an exploit and execute it in memory after the page loads? or something else just as bad? inline is inline, blind trust is just blindness and good feelings. – Stof Jul 17 '23 at 08:36
2

Building on @Mitya answer.

In most of the modern JS libraries React, Vue,..etc. inline event handlers are considered idiomatic, but most of the limitation mentioned by @Mitya are gone. As case study we will have look over Vuejs and compare it with point listed above:

  1. You can have more than one event-handler, look here
  2. Event values (handlers) such as onclick are not plain string but js expressions look here
  3. Global Scope problem simply does not exist (because your code will get translated minifed, repackaged by tools such as webpack or other).

In my own opinion, inline event handler enhance readability majorly, but opinions may vary.

tony19
  • 125,647
  • 18
  • 229
  • 307
adnanmuttaleb
  • 3,388
  • 1
  • 29
  • 46
  • 7
    React, Vue and Angular might look like they are using "inline event handlers" but they are _not_ using an HTML _attribute_ as described in the original question. They are using _directives_ and under the hood they will be using `addEventListener `. Thus complying with best practise: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these – Colin Oct 11 '21 at 17:26
  • 2
    @Colin Can't tell you how many times I've had to explain that to those who want to put these directives up as examples of why it's actually ok to use HTML event attributes (which is is not)! – Scott Marcus Jan 03 '23 at 18:23