Accumulate HTML

Keywords: 
Situation: 

Some HTML will get longer and longer as things happen on the page.

Actions: 

When something relevant happens, append HTML to a variable. Inject the variable into the page.

Explanation: 

This example, adapted from the Better pig lesson.

First, create a variable to be the accumulator:

var auditTrail = "";

It starts out empty, or with some initial HTML, like:

var auditTrail = "Here is the audit trail.<br>";

When something relevant happens, create some new HTML, and append it to the accumulator:

auditTrail += "Something happened that we want to remember.<br>";

You can send the accumulator to a server, inject it into the page, or whatever is needed.

It's common to create a function to collect the new HTML, like this:

BetterPiggyBank.logTransaction = function(message) {
    auditTrail += message + "<br>";
    $("#audit-trail").html(auditTrail);
};

Call it like so:

BetterPiggyBank.logTransaction("We fed the pig.");