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

Are inline event handlers bad practice?

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

If so, what are the disadvantages of using built-in event handlers?

+8
source share
2 answers

This is a bad idea because ...

1) For a long time there was a reasonable emphasis on a clear separation between content, style and script. Muddying your JS HTML is not consistent with this.

2) More importantly, you have much less control over your events. In particular:

  • you can only associate one event of each type with DOM-zero events (these are what are built-in), so you cannot have two click event handlers

  • If an event is specified in a string, JS is indicated as a string (attribute values ​​are always strings) and evaluated when the event fires. Assessment of evil.

  • You are faced with the need to reference named functions. This is not always ideal (event handlers usually accept anonymous functions) and have implications for the function, which should be global

In short, handle events centrally through the dedicated addEventListener API or through jQuery or something like that.

+13
source

In addition to the semantics and other opinions expressed in the accepted answer, all embedded scripts are considered a vulnerability and a high level of security. It is expected that any website that expects to work in modern browsers will set the Content-Security-Policy (CSP) property, either through a meta attribute or in the headers.

This is incompatible with all built-in scripts and styles unless explicitly resolving them as an exception. Although the goals of CSP are primarily to prevent persistent cross-site scripting (xss) threats, for which inline scripts and styles are an xss vector, this is currently not the default behavior in browsers, but may change in the future.

+1
source

All Articles