Why Is Using Onclick() in HTML a Bad Practice

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

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:

$('#someLink').click(function(){
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

Is using onClick={} considered a bad practise?

The onclick attribute in HTML is considered a bad practice because it decouples the function from the place where it was called from (among other things). If you read through the related JS files, it is unclear where a certain function was called from, and therefore its purpose is unclear. If you use .addEventListener from within JS, you keep the function and the purpose (the events that trigger it) together.

Reacts purpose is to keep the logic and the view together, so there is no decoupling possible at all. Therefore it is totally fine to use onClick, and it's the only right way I can think of.

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.

is it bad practice to use href='javascript:func()' than onclick='func()' for anchors?

Neither.

Use this:

<a href="javascript-disabled-page" onclick="func(); return false;">blah</a>

That way if the user has JS disabled, they will be taken to javascript-disabled-page and the browsing experience isn't ruined.

Is creating objects in html and having functions considered bad practice in oop?

The problem with using old-style onxyz-attribute event handlers is that you can only use global functions in them. The global namespace on browsers is very crowded, and so it's best to avoid adding more to it when you can avoid it.

In your example, you might consider ensuring that the button can be identified with a CSS selector (or an id) and then hooking up your handler using modern techniques like addEventListener:

const theButton = document.querySelector("selector-for-the-button"); // or = document.getElementById("the-button-id");
theButton.addEventListener("click", function() {
const name = new Person('first_name', 'second_name', 'output');
name.writeName();
});

That way, Person doesn't have to be global.

This is particularly useful when combined with modules (whether JavaScript's native modules or those provided by Webpack, Rollup, and similar).

Here's a complete example, notice that it doesn't use any globals:

{ // Scoping block to avoid creating globals    class Person {        constructor(first_name_id, second_name_id, output_id) {            this.first_name = document.getElementById(first_name_id);            this.second_name = document.getElementById(second_name_id);            this.output = document.getElementById(output_id);       }       writeName() {           return this.output.innerHTML = "Your name is " + this.first_name.value + " " + this.second_name.value;       }    }        document.getElementById("show-name").addEventListener("click", function() {        const name = new Person('first_name', 'second_name', 'output');        name.writeName();    });}
<input id="first_name" type="text" placeholder="First Name"><input id="second_name" type="text" placeholder="Second Name"><button id="show-name">Show name</button><p id="output"></p>

Is JavaScript as HTML Attribute Bad Practice?

It is not wrong, per se, but yes, it is seen as bad practice by the vast majority of people.

Good practice is to separate the HTML and Javascript as much as you can. It is the same concept as with CSS. Mixing up the HTML, CSS and Javascript in the same file can become unmanageable very quickly, and should be avoided, if at all possible.

Ideally, the two should be in separate files (.html and .js files), but separating them in the HTML is a good first step.

You can separate the two by using event listeners, like so:

<!-- The elements -->
<span id="valBox">25</span>
<input id="inputBox" type="range" min="5" max="50" step="1" value="25">

<script>
// Grab the elements here
var val = document.getElementById("valBox");
var inp = document.getElementById("inputBox");

// Add an event listener to the input element and
// set the span value when it changes
inp.addEventListener("change", function () {
val.textContent = this.value;
});
</script>

See this answer if you need to support IE<=9.

onclick= vs event handler

Basically it has to do with the whole keep everything separate I believe. So keep HTML/CSS/JS all separate. It makes your HTML tidier and, I think, easier to navigate without.

Then when/if you need to make large changes, you have ample space with having to shift the inline JS to an external file anyway OR if you want to apply the same function to more than one button, then it's less code. And less code is a happier place

If you have your JS files properly, and thoroughly documented then navigating them by an outside person is made eaiser



Related Topics



Leave a reply



Submit