Adding onclick() to passage links in Sugarcube

Twine Version: 2.6.1
Sugarcube 2.36.1

Hi there,

I’m implementing xAPI in a learning game

What I want to do is change a variable based on what the user clicks, and then trigger a javascript function using an onclick() event in a passage link.

I can achieve what I want with vanilla HTML and JS (though I’m not sure how to link to another passage without making use of any shortcodes); I’d like to see if I can do this with the built-in shortcodes as I have many of these passages to create.

Something like this would be lovely:

<a data-passage="Next Passage" data-setter="$multipleChoiceSelection to 'Steak'" onclick="send_multiple_choice()">Steak</a>

However, the onclick() event gets stripped out in the generated HTML file.

Any clues? Is this possible?

Thanks!

1 Like

Based on the fact that your <a> element example includes both a data-passage property and a tag onclick event handler, you seem to be trying to have two things happen when the end-user selects that link:

  1. a normal Passage Transition to the Next Passage.
  2. the execution of the send_multiple_choice() JavaScript function.

…and not necessarily in that order.

One issue is that the SugarCube engine uses a ‘click’ event handle on the element to execute the code that does the Passage Transaction, and I doubt that the code that attaches that engine related event handle to the element in question knows how to chain any event handler already attached to the ‘click’ event. So it is likely that your tag based ‘click’ event handler is being replaced by the engine’s.

If you do want your send_multiple_choice() function to be executed before a Passage Transition to Next Passage occurs then simply use a standard <<link>> macro call like the following…

<<link "Steak" "Next Passage">>
    <<set $multipleChoiceSelection to 'Steak'>>
    <<run send_multiple_choice()>>
<</link>>
2 Likes