[solved] twine Sugarcube javascript sheet help

Frogface29

Newbie
Feb 22, 2022
43
41
Hey, just a heads up, i am very new to javascript and twine. The goal of my javascript is to play the video with the video id="myVideo" only when it appears on the users screen. The javascript i have works fine when posted in the script section of the passage where the video is at. However, it fails when i post it to my javascript sheet. Why is that?

working code when posted in passage:
You don't have permission to view the spoiler content. Log in or register now.
does not work when simply copied to the javascript sheet like this:
You don't have permission to view the spoiler content. Log in or register now.

why is that, and how do i fix this? I do not want to put the whole script into every passage where i use a video, i would rather have that script in the javascript sheet.
thanks,
 

Alcahest

Engaged Member
Donor
Game Developer
Jul 28, 2017
3,135
4,032
The javascript section is only run once -- when you start the game/refresh the browser. If you want to put the video functions in the javascript section, you have to do something to run it every passage. There are a number of ways to do this.

For instance, by calling the code from the PassageDone special passage. Put the two functions in the javascript section, then also add this to the javascript section:
Code:
setup.startObservingVideo = function() {
    var target = document.getElementById("myVideo");
    videoObserver.observe(target);
}
Then add this in the PassageDone special passage:
Code:
<<script>>
    setup.startObservingVideo();
<</script>>
This shows why you should use <<script>> instead of <script>. Because then you can access Sugarcube objects, like the setup object, and the State object (variable $name can be accessed with State.variables.name in the javascript section. State.temporary for temporary variable names, eg _name).

Be aware that you shouldn't use // comments in passages. Use /* */ or the comments can break the code (can vary depending on computer setup/browser). If I copy your code and run it in a passage, it won't run until I change all four // comments to /* */ comments.
 
Last edited: