DEV Community

Steve P.
Steve P.

Posted on

Keeping HTML and JavaScript (and CSS) Fully Separated

This is a submission for DEV Challenge v24.03.20, One Byte Explainer: Browser API or Feature.

Explainer

In a total very useful separation of concerns, all devs can and should keep all JavaScript and CSS out of HTML markup--not using "on-" event handlers--using DOM element 'id' attribute, largely using the always handy document.getElementById method.

Additional Context

Do web devs still define event handlers in HTML markup, written in an element attribute?

/myEntryPage.html
<input type="radio" name="colorSelect" value="red" onchange="selectColor(this);"> Red
<input type="radio" name="colorSelect" value="blue" onchange="selectColor(this);"> Blue
Enter fullscreen mode Exit fullscreen mode

Instead all devs should use the HTML id attribute (rarely the class attribute when needed) along with the JavaScript DOM methods document.getElementById() and document.addEventListener() to set up document elements with event handlers, rather than using "onclick=" or "onchange=" (or any "on-") element attributes. JavaScript (and particularly the highly recommended TypeScript) is not usually subject to error/code-checking if using script of any kind defined as an element attribute or even with multiple line/statements enclosed in <script> tags. The above markup has been re-coded below to fully remove JavaScript from HTML markup and put it properly into *.js (or *.ts) files. The script shown is TypeScript (highly recommended) so the event handlers are initialized on page load.

/myEntryPage.html
<input type="radio" id="colorSelect-red" value="red"> Red
   <!-- id="colorSelect-red" CHANGE="selectColor(this);" -->
<input type="radio" id="colorSelect-blue" value="blue" onchange="selectColor(this);"> Blue
   <!-- id="colorSelect-blue" CHANGE="selectColor(this);" -->

/myEntryScript.ts
document.addEventListener("DOMContentLoaded", (/* event: Event */) => {
   document.getElementById("colorSelect-red").addEventListener("change", (event: Event) => {
      selectColor(event.target as HTMLInputElement);
   });
   document.getElementById("colorSelect-blue").addEventListener("change", (event: Event) => {
      selectColor(event.target as HTMLInputElement);
   });
});
Enter fullscreen mode Exit fullscreen mode

(Note, to track elements in markup with event handlers, you might put an HTML comment underneath with the 'id' of the element and the event CAPITALIZED with its code as an aid in documenting/annotating.)

Top comments (0)