Call and execute a function before unloading a page in Twine 1.4.2 / Sugarcube 2

Twine Version: 1.4.2
Story Format: Sugarcube2
Author: total noob

I’m trying to get the text on the page to hide itself sequentially after clicking a button (it has to be a button for the UI to look right) which follows a link to a new passage, but before the link is actually followed. (so it looks like the text is disappearing gradually, and then the next passage loads)

I’m sure I’m doing something stupid - I’m getting it to display itself sequentially when the passage loads using document.addEventListener(“load”, showText()) - showText() is a function that cycles through a set of span elements and sets style.visibility to visible, using setTimeout to make them appear in sequence.

I’ve written a similar function which successfully hides the span elements in sequence when I attach it to an HTML button (which doesn’t follow a link), but I can’t find a way to attach it to a Sugarcube button which does follow a link.

I can’t find a way to do it (using Sugarcube macros or Javascript - either would be fine as long as it works) before the link is followed when I click the button. I must be missing something obvious?

Any help gratefully received.

There might be a better way to do this, but off the top of my head, there are two ways to tackle this.

For the first method, you can use the passageinit event that is called before the new passage is rendered. You can find the documentation here.

Example from docs:

$(document).on(':passageinit', function (ev) {
	/* JavaScript code */
});

For the second method, you can forego the standard passage links and use the <<link>> macro to execute a javascript function. In that function you can hide the elements like you want, followed by the Engine.play("passage-name") function to navigate to the passage when it’s finished.

You could also make your own widget or macro for it so it’s not annoying to use over and over.

Anyway, those are my thoughts on it.

Hi tayruh,
Thanks - I used Engine.play() and then all I had to do was work out how to style the link so it looks and behaves like a button. Works a treat!

1 Like

FYI - If you want to use a button, then you should use the <<button>> macro instead, for accessibility reasons (i.e. so that it works better for blind users).

1 Like