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?
It's a bad idea because...
Best practice suggests a clear split between content, style and script. Muddying your HTML with inline JavaScript (or CSS) is not consistent with this.
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.
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.
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).
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.