Making history

If we can change text in a element, we also can add a completely new node in the DOM structure of a page.

We can use this feature to dinamically change the content of our HTML page to show live the decisions we are taking.

In our HTML we add a couple of buttons, as a way to take decisions:

<p>
<input type="button" id="btnLeft" value="Left" onclick="cmdButton(true)" />
<input type="button" id="btnRight" value="Right" onclick="cmdButton(false)" />
</p>

At bottom page we add a div section, where we are going to put the decisions history:

<div id="history">
</div>

In the script tag we add a variable definition, to keep track of the current step:
var currentStep = 0;
Then we define the function called to react to the buttons onclick event - currently it doesn't do much, just increasing the current step and calling a function that add a new entry in the history section:

function cmdButton(left) {
++currentStep;
setHistory(left);
}

And finally here is the real point of interest of this post. In setHistory() we get the node where we keep the history, create a new "p" element, adding to it a new text child, containing the information that we want to store, and then appending the "p" element to the history:

function setHistory(left) {
var history = document.getElementById("history");
var newNode = document.createElement("p");
var newText = document.createTextNode("Decision " + currentStep +
": you clicked " + (left ? "left" : "right"));
newNode.appendChild(newText);
history.appendChild(newNode);
}

More details on DOM in chapter eight of Head First JavaScript.

No comments:

Post a Comment