Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Passing twine variable to JavaScript?

G'day Everyone,

In our story the reader accumulates certain values for a set of variables. At the end of the story we want to use these values to create a JavaScript chart. We are having problems passing the variables values that are in our twine story to a JavaScript function for creating the graph.

We are using Harlowe in Twine 2.

In the HTML we are including the following:
<button onclick="myFunc(jsVar)">Push Me</button>

This is calling a JavaScript file with the following code:
function myFunc(jsVar){
alert("Hello" + jsVar)}

In the head we are also defining jsVar:
<script>var jsVar = $values</script>

This JavaScript file is a separate file that we are linking to in the head of the Twine HTML file, because we couldn't figure out how to call JS functions using the Story JavaScript stuff in Twine.

We are getting an alert that says "HelloUndefined". We would love some help in defining jsVar! Much appreciated.

Regards,
Adam and Carly

Comments

  • All your issues are due to you trying to access variables and methods in different scopes:

    This comment explains about handling the scope of custom Javascript methods.

    Harlowe does not currently have a documented Javascript API but you can use the (print:) macro to dynamically create your button in a way that allows you to pass the values stored in story variables to your javascript method.

    1. Add the following to your Story Javascript area, it creates an simple method that outputs a value to the web-browser console.
    if (! window.My) {
    	window.My = {
    		console: function (values) {
    			if (values) {
    				console.log('values: ' + values);
    			}
    		}
    	}
    }
    
    2. Add the following to a passage, it first defines some variables and then uses a (print:) macro to dynamicall create a button element that uses the method created in point 1.
    (set: $var1 to "A")
    (set: $var2 to "B")
    (set: $var3 to "C")
    
    (set: $values to (array: $var1, $var2, $var3))
    
    (print: "<button onclick=\"My.console('" + $values.join(',') + "')\">Push Me</button>")
    
  • Thanks a lot Greyelf your answer was very useful! We now have some cool graphics at the end of our educational story that provides students with a snapshot of where they are at. :-)

    All the best,
    Adam & Carly
Sign In or Register to comment.