Howdy, Stranger!

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

How to call js functions with SugarCube 2 [Twine 1]?

I've got this function in my "script" passage:
function fadeInText(id, delay) {
var elem = document.getElementById(id);
setTimeout(function () {
elem.style.opacity = 1;
}, delay * 1000)
}

I would like to call it in passages to fade in specified text areas or other elements on entering the passage (selected via <div id="...">)

I'm very frustrated as I simply cannot call that function from my passage. I've tried calling it using <<script>> or via <<run>>, but I only get errors such as "expression not defined" or unspecified js errors. Is it not possible to call a JS function from out of a passage? What is my mistake? I also couldn't find any section in the SugarCube documention that clearly addresses my question.

Comments

  • First. In the future, if you're asking for help with code, post the whole unadulterated code itself, not parts of it, not screenshots of it, etc. When you do, please use the code tag—it's C on the editor bar—when posting code or markup, rather than the quote tag.


    Your function is executed within its own self-contained scope. You'd need to attach it to an object visible to the rest of SugarCube to be able to call it via <<script>> or <<run>>. You may use SugarCube's own setup object for this purpose or the window object, which will make the function an auto-global. Beyond that, you'd have to call it from a postdisplay task, since the rendered passage isn't added to the page until just before—i.e. as written, you couldn't call it from <<script>> or <<run>> and have it work, since the element you're attempting to select isn't part of the document yet.

    That said, you're probably better off using CSS or the <<timed>> macro to for what it appears that you're attempting to do here—fade in some text after a passage has been displayed.
  • I'm sorry, but I'm very aware of what you mention in 'first' and I'm not new to this forum.

    Otherwise, thank you for the information.
Sign In or Register to comment.