Javascript – How to write JavaScript while keeping HTML/CSS out of it

htmljavascriptjqueryjsonseparation-of-concerns

What is / are some recommended ways to write JavaScript as to control behavior of showing HTML on screen, while keeping well-maintainable code? Basically, I started to look for ways to keep HTML/CSS out of JS (assuming it's the recommended practice), but I might as well check into the latest ways of writing JavaScript well. See below for more details.

My specific problem

I have JS files that look something like this:

var selection = eval("(" + document.getElementById("result").innerHTML + ")");

if (selection[index].selected) {
    result += '<TABLE class="list_grey" style="float: left; margin-left: 20px;">';
    result += '<TR>';
    result += '<TH colspan="2">Data</TH>';
    result += '</TR>';

    var flag = "All";

    if (selection[index].flag == 'P')
        flag = "Premium";

    result += '<TR>';
    result += '<TD>Flag</TD>';
    result += '<TD>' + flag + '</TD>';
    result += '</TR>';
    result += '</TABLE>';
}

document.getElementById('final').innerHTML = result;

In fact, entire JS codebase I work with is plagued by this. You can see here HTML, CSS JS, and JSON (selection var gets its content from JSON prepared by PHP earlier). I want to make this better.

My experience level

I am new to writing good JS or to having experience with JS patterns, tools, tips, techniques, and so on. I am looking for help with those.

My specific issue:

I have a series of tables and data to be shown to the user. It is a "series", so user can select which "element" of the series is currently active on the screen. An "element" is essentially an HTML partial (with JS and CSS and HTML), and is described below:

"element": a block of HTML that serves as static data (tables, titles, and divs), and a long JSON string that encodes some previously prepared data. JSON string is assigned to a JS variable and that JSON data/JS variable stores records numbered 1 through n, where each i holds various data to be injected into the block of HTML, forming "HTML partial".

I have navigational buttons on the screen, allowing user to step through the "series", where the HTML is the same, but the data inside it changes.

I am looking for a good way to write this "step through HTML blocks" functionality using what is considered to be good maintainable JS code. Namely, I am looking for the following characteristics:

  • separation of concern
  • cleaner code – I need tools or techniques to allow me to avoid mixing HTML with JS with CSS (as in seen my example), unless where necessary or convenient. (what I have now is not convenient)
  • I prefer techniques rather than tools, but open to considering/evaluating well-established tools. By "techniques", I mean pure JS, HTML, CSS, PHP approaches. By "tools", I currently know and trust jQuery, and for other tools prefer to have some track record to them.

Note on HTML visibility/hiding

I should also perhaps note that in my case HTML is static, aka it does not change structurally, as I step through the elements. However, based on the JSON/selection variable, some blocks of HTML are show/hidden (as is shown in my example). Once they are shown/hidden at page render time, they stay shown/hidden throughout stepping through selection.

Best Answer

Use a mvw (model/view/whatever) pattern

  • model: "pure" javascript library modelling abstract concepts. This part usually contains objects & methods names related to the application domain (car business -> car objects / insurance contracts) and the data access logic.
  • view: a custom language describing how your UI look like. Preferably, the language should be close to HTML.
  • something to make both part communicate without having one depend too much on the other. A change in the model data must result in a change in the corresponding elements of the view (model -> view). A mouse click mouse result in a method call somewhere in the model (view -> model).

With those concepts, you can choose different stacks

  • You can use a big framework such as angular. The views are html dom template. The model is divided between controllers & services.
  • you can use backbone (~model) + jquery (~view)
  • you can use react.js

... the list goes on. The number of tools available is actually pretty scary. Check http://todomvc.com/ for a nice list of examples.

Example solution with angular

In angular, the connection between the model & the view is performed with a viewmodel & dual way data binding. A view model is a javascript object. Both the view & the model can read & write to this object, and react to changes.

in your view, you write the HTML:

<TABLE class="list_grey" style="float: left; margin-left: 20px;" ng-hide="hideAll">
<TR ng-repeat="row in rows">
    <td ng-repeat="val in row" ng-class="{selected : val.sel}"> {{ val.label }} </td>
</TR>
</TABLE>

in your controller, you only deal with javascript values:

$scope.rows = [
    [{label : "foo"}, {label : "bar"}],
    [{label : "foo2"}, {label : "bar2", sel : true}]
]

$scope.hideAll = false;

ng-repeat allows you to display a list of items. ng-class & ng-hide are used to control the class & visibility of the elements.

Closing words

Using other frameworks, the resulting organization may vary, but the essential separation still exists. In react.js, the data binding is unidirectional, which implies different construct. The mvw framework usually deals with the communication between the components, so you don't have to use jquery at all.

This is a good thing if your project isn't trivial. Managing a complex app with only jquery can lead to a mess of callback interactions which may become hard to maintain.

Using a full mvw framework such as angular or ember requires some learning. Some other libraries have a smaller scope such as react.js & knockout.js.

Of course you don't have to start learning one of these tools right now. The important thing is to achieve the separation between the view & the model. You can use jquery to write functions which will edit the dom according to observation made on a pure javascript library.

You can also use jquery to write the (view -> model) callbacks. (model -> view) can be written using publisher/observer. This part should be as small as possible, and be the only thing connecting the model and the views.

Related Topic