One option would be to use hashkey navigation.
Have the links point to href
's beginning with a #
followed by the label of the next line of dialog.
The original intended purpose of this syntax are links within a HTML document. But the fact that clicking on them does not trigger a page reload makes them very useful for Javascript single-page applications like yours. They trigger the window.onhashchange
event, which can then check location.hash
to get the href of the link the user clicked on.
Here is a little proof-of-concept consisting of a javascript snippet which must run on page load and a piece of HTML which uses it:
window.onhashchange = function() {
alert("You clicked on " + location.hash);
}
<a href="#Answer1">Click!</a>
<a href="#Answer2">Click!</a>
<a href="#Answer3">Click!</a>
But hashkey links have a side-effect you should be aware of: They generate history-entries in the user's browser history. See what happens when you run the code snippet above, click on some of the links and then click your browser's back-button. The user can navigate back and forth in your story using their web browser.
Another option which doesn't have this side effect is to use click handlers instead of links.
Create a HTML node (I would recommend a <button>
, but it works with any visible node) and then assign an .onclick
event handler to it.
function display_answers(varStore) {
var container = document.getElementById("container")
varStore.forEach(function(answer) {
var answerButton = document.createElement("button");
button.innerHTML = answer.m;
button.onclick = function() {
goto(answer.next);
}
container.appendChild(button);
});
}
Note that I am using the Array.prototype.forEach
function instead of a for
-loop. That's not just a stylistic choice. This pattern makes sure that the current value of the variable answer
is captured when the new anonymous function is created which then gets assigned to the onclick-handler.
This code also calls a new function goto(label)
which you will have to implement on your own. But that shouldn't be hard: it needs to do the same thing execute_game()
does, just start from the given label and not from line 0.