Michael Schwartz Michael Schwartz - 1 year ago 82
HTML Question

Is JavaScript as HTML Attribute Bad Practice?

Example: http://stackoverflow.com/a/37289566/710887

I see this happening more and more often.

I was always taught to keep javascript, css, and html separate (with html linking to the sources/scripts of course).

Is using an Javascript in an HTML attribute (such as

onclick, onchange, etc:
) bad practice?

<span id="valBox">25</span>
<input type="range" min="5" max="50" step="1" value="25" onchange="valBox.textContent = this.value">

Answer Source

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

    // 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;

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