Why is using onClick() in HTML a bad practice?

  1. Home
  2. javascript
  3. Why is using onClick() in HTML a bad practice?

I have heard many times that using JavaScript events, such as onClick(), in HTML is a bad practice, because it’s not good for semantics. I would like to know what the downsides are and how to fix the following code?

<a href="#" onclick="popup('/map/', 300, 300, 'map'); return false;">link</a>

First answer

You’re probably talking about unobtrusive Javascript, which would look like this:

<a href="#" id="someLink">link</a>

with the logic in a central javascript file looking something like this:

    popup('/map/', 300, 300, 'map'); 
    return false;

The advantages are

  • behaviour (Javascript) is separated from presentation (HTML)
  • no mixing of languages
  • you’re using a javascript framework like jQuery that can handle most cross-browser issues for you
  • You can add behaviour to a lot of HTML elements at once without code duplication

Second answer

It’s not good for several reasons:

  • it mixes code and markup
  • code written this way goes through eval
  • and runs in the global scope

The simplest thing would be to add a name attribute to your <a> element, then you could do:

document.myelement.onclick = function() {
    window.popup('/map/', 300, 300, 'map');
    return false;

although modern best practise would be to use an id instead of a name, and use addEventListener() instead of using onclick since that allows you to bind multiple functions to a single event.

Third answer

With very large JavaScript applications, programmers are using more encapsulation of code to avoid polluting the global scope. And to make a function available to the onClick action in an HTML element, it has to be in the global scope.

You may have seen JS files that look like this…

    ...[some code]

These are Immediately Invoked Function Expressions (IIFEs) and any function declared within them will only exist within their internal scope.

If you declare function doSomething(){} within an IIFE, then make doSomething() an element’s onClick action in your HTML page, you’ll get an error.

If, on the other hand, you create an eventListener for that element within that IIFE and call doSomething() when the listener detects a click event, you’re good because the listener and doSomething() share the IIFE’s scope.

For little web apps with a minimal amount of code, it doesn’t matter. But if you aspire to write large, maintainable codebases, onclick="" is a habit that you should work to avoid.

Spread the love

Related articles

Comments are closed.