SugarCube 2: Outputting a variable using textContent

Hi all,

I’m slowly teaching myself some Twine but am a bit confused as to why the code below doesn’t work. I am trying to code a button that changes the text on another part of the page. The first button does this directly but the second when I try to use textContent it says $atkResult is not defined?

<<set $atkResult to "You swing and hit!">>

<<button "Test">><<script>>document.getElementById("resultBox").textContent = "New text test";<</script>><</button>>

<<button "Attack">><<script>>document.getElementById("resultBox").textContent = $atkResult;<</script>><</button>>

<p id="resultBox">Initial text</p>

Within JavaScript code (which is what the code inside <<script>>...<</script>> is treated as), use State.variables instead of $ to refer to story variables. The second button should work if you change it to <<button "Attack">><<script>>document.getElementById("resultBox").textContent = State.variables.atkResult;<</script>><</button>>.

In addition to what Agat said, you could be doing things far more simply by using either jQuery (which is included with SugarCube) or the SugarCube <<replace>> macro. For example:

<<set $atkResult = "You swing and hit!">>

<<button "Test">>
	<<run $("#resultBox").empty().text("New text test")>>

<<button "Attack">>
	<<replace "#resultBox">>$atkResult<</replace>>

<p id="resultBox">Initial text</p>

The “Test” button uses the jQuery .empty() method to clear out the contents of the “resultBox” <span> and then the .text() method to add in new text. The “Attack” button uses the <<replace>> macro to do the same thing.

Since those are both run from either inside of a macro or in the passage’s text, they still have full access to SugarCube variables. As you can see, you can use the <<run>> macro as a replacement for putting a line of JavaScript code inside of a <<script>> macro, and it has the added advantage of not needing to use State.variables or State.temporary to access SugarCube story or temporary variables, respectively, as Agat explained are required within a <<script>> macro.

Hope that helps! :slight_smile:

Brilliant, thanks for all the pointers :grinning: