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?
An event handler is a JavaScript function that runs when an event fires. An event listener attaches responsiveness to a given element, which allows the element to wait or “listen” for the given event to fire. Events can be assigned to elements via inline event handlers, event handler properties & event listeners.
addEventListener() has multiple advantages: Allows you to register unlimited events handlers and remove them with element. removeEventListener() . Has useCapture parameter, which indicates whether you'd like to handle event in its capturing or bubbling phase.
You can attach an event handler content attribute to the HTML element for which you want to respond to when a specific event occurs. For example, you could attach the onmouseover event handler content attribute to a button and specify some JavaScript to run whenever the user hovers over the button.
In html, there are various events which represents that some activity is performed by the user or by the browser. When javascript code is included in HTML, js react over these events and allow the execution. This process of reacting over the events is called Event Handling.
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 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.
You are faced with having to reference named functions. This is not always ideal (event handlers normally take anonymous functions) and has implications on the function needing to be globally accessible
Your content security policy (CSP) will 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With