In JQuery how can I keep HTML OUT of my javascript?

411 views Asked by At

I think JQuery is great but I also like the idea of keeping the HTML in the HTML document and virtually none of it in the javascript. What do I mean? You know like, say you are creating a dynamic table that had many many rows or a variable number of rows. This is exactly what I DON'T want to do:

function initBoard(symbol) {
    for (var i=0;i<30;i++) {
        myBoard += "<tr>";
        enemyBoard += "<tr>";
        for (var j=0;j<60;j++) {
            myBoard += '<td bgcolor="#0000ff" id="my_sqr_'+i+'_'+j+'">'+symbol+</td>';
            enemyBoard += '<td bgcolor="#ff0000" id="enemy_sqr_'+i+'_'+j+'">'+symbol+'</td>';
        }
        myBoard += "</tr>";
        enemyBoard += "</tr>"
    }
    $("#my-board").html(myBoard);
    $("#enemy-board").html(enemyBoard); 
}

A few years ago I came up with a solution that almost works well and I frequently use it but I'd still like to see something better and that's what my question is about. My current strategy is to create a hidden div at the bottom of the main HTML file. For example:

<div class="hidden-templates" style="visibility:hidden;">
    <div id="board-line-tpl">
        <td bgcolor="--bg-color--" id="--side--_sqr_--index1--_--index2--">--symbol--</td>
    </div>
</div>

and then the javascript is changed to something like this:

function initBoard(symbol) {
    for (var i=0;i<30;i++) {
        myBoard += "<tr>";
        enemyBoard += "<tr>";
        for (var j=0;j<60;j++) {
                    // Get the template
            myBoardLine = $("#board-line-tpl").html();
                    // substitue the template's"variables" with unique data
                    myBoardLine.replace(/--side--/, "my");
                    myBoardLine.replace(/--bg-color--/, "#0000ff");
                    myBoardLine.replace(/--index1--/, i);
                    myBoardLine.replace(/--index2--/, j);
                    myBoardLine.replace(/--symbol--/, symbol);
                    myBoard += myBoardLine;
                    // You get the idea.  I'll leave this line as is.
            enemyBoard += '<td bgcolor="#ff0000" id="enemy_sqr_'+i+'_'+j+'"></td>';
        }
        myBoard += "</tr>";
        enemyBoard += "</tr>"
    }
    $("#my-board").html(myBoard);
    $("#enemy-board").html(enemyBoard); 
} 

OK, one thing you notice that sucks about my solution is quite a bit more verbose but in fairness, it does seem to shine if your template has any sort of complexity. A good candidate for a template is HTML having 5 or more lines. Another thing in it's favor is it does do the job of getting HTML out of the Javascript. Now I can let my HTML designer edit the HTML in the hidden-template div, and change the look of it and put classes in as desired (It was easy to teach him about the templates and what they do) and so now he doesn't have to touch the Javascript. However, lately I've been running into some problems with defining whole tables as a template. As JQuery reads the template it tries to reinterpret the table code and it screws it up.

2

There are 2 answers

0
mrtsherman On

jQuery provides a syntax where you can specify attributes at the time of element creation. This should provide the clean look you want.

$('<tr />', {
    id: 'foo',
    class: 'row'        
});

You may also want to look into storing the board x/y attributes in a data object as opposed to embedded in the id.

$('<tr />').data('x', xval); //set data property
var xval = $(element).data('x');

Here is an example based on your code:

http://jsfiddle.net/YAHDK/

var $table = $('<table />');    

for (var i = 0; i < 30; i++) {
    var $row = $('<tr />');

    for (var j=0;j<60;j++) { 
        var $td =($('<td />', {
            id: i + '_' + j,
            bgcolor: '#0000ff',
            text: i
        }));
        $row.append($td);      
    }

    $table.append($row);
}


$('body').append($table);
0
King Friday On

try jsRender, jsViews or jQuery templates

These are the templated solutions that separate JavaScript and HTML quite well. I use jQuery templates myself and I find it a huge time saver as I don't have to worry about HTML inside JavaScript and my code is literally 80% smaller in not having HTML. The code is also way easier. Just spend a few moments to check templating out. Its well worth it.

Note that jQuery templates are being abandoned for jsRender and jsViews but jQuery templates works very well for now for what you need to do and the move to jsRender or jsViews will be simple in terms of concepts, not much change in terms of understanding and syntax.