Why Are Inline Event Handler Attributes a Bad Idea in Modern Semantic Html

Why are inline event handler attributes a bad idea in modern semantic HTML?

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 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. 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

  5. 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.

When I click on the button it shows me an error

no need to do a form for this, also inline events are not preferred use eventListeners in js.

NOTE: I've put input's value as result, but you didn't say what you exactly want, so I think this will work with you anyway

document.getElementById('l').addEventListener('click', function() {
document.getElementById('result').innerHTML =document.getElementById('k').value;
})
<label>How much do you want to donate</label>
<input type="number" id="k">
<button id="l">Cal</button>
<p id="result"></p>

Inline event handler practice javascript

This is a question of "separation of concerns", and your component is generally separated into a file, which then contains the "control" of that component.

Angular directives are basically an idea that builds upon this in your templates.

In-lining it into the html without such a system of functionality (like angular) is akin to writing your entire html templates in your javascript --- bad, unless you have a system that is helping you do that.

Basically, without angular you should "keep your javascript in your javascript" and your "html in your html".

Read further about MVC and separation of concerns at

https://www.safaribooksonline.com/library/view/programming-javascript-applications/9781491950289/ch05.html

Angular’s controllers might remind you a lot of models from other MVC
implementations, if you’re a follower of the “fat models, skinny
controllers” approach.



Related Topics



Leave a reply



Submit