Howdy, Stranger!

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

How to add additional JS scripts to Harlowe…

Hi,

I’ve been wondering this for a while… How can we add additional JS scripts (like jQuery plugins) to Harlowe by linking to them?

I have tried the jQuery method:
$(function () {
    $.getScript("http://link.to/js/file.js", function (data, textStatus, jqxhr) {
        console.log(data); // Data returned
        console.log(textStatus); // Success
        console.log(jqxhr.status); // 200
        console.log("Typed was loaded.");
    });
});
…but it doesn’t seem to work.

Is there a "proper" way to do this within Twine? Or do I have to do it after the fact in the published HTML?

Thanks,
Tim

Comments

  • Ah! I found out that this is working… In order to use it, all dependent scripting needs to go in that function itself and not outside of it.

    Cool. :)
  • timsamoff wrote: »
    Ah! I found out that this is working… In order to use it, all dependent scripting needs to go in that function itself and not outside of it.

    Cool. :)

    Could you clarify what you mean by that, and provide an example?

  • Yes, please. This would help others running into the same problem. Thx!
  • edited May 2015
    Ah, yes, sorry...

    Use the jQuery getScript() function to call the external JavaScript file from wherever it's located. Then, within the function itself write in any of the script-specific calls that are required. So...
    $(function () {
        $.getScript("http://link.to/js/file.js", function (data, textStatus, jqxhr) {
            // This stuff is unnecessary,
            // but lets you know what's
            // happening 
            console.log(data); // Data returned
            console.log(textStatus); // Success
            console.log(jqxhr.status); // 200
            console.log("Typed was loaded.");
            // Put any script-specific calls in
            // here as well
            $('someSelector').script(function(){});
        });
    });
    
    I'm writing this from my head on a mobile device, do let me know if you need a more detailed example.
  • Ok... Still not sure I understand which is annoying as I think it could be the answer to my problem....
  • edited May 2015
    Well, a little bit of experience with JavaScript and jQuery is necessary, but let me offer a real-world example without all of the superfluous "checks" in the code…

    I’m currently working on a game in which I wanted the title to appear on the screen as if being typed. To do this, I chose to use the typed.js jQuery plugin (http://www.mattboldt.com/demos/typed-js/). In order to use typed.js, one must first import the jQuery library (which Twine already does). Then, typed.js must be imported as well… After that, the typed.js function must be called when the web page loads.

    To accomplish this, typed.js must reside at an Internet location (lets say you have a web server at http://twinerocks.com). On that server, you add a folder named "js" (to store JavaScript files in) and you upload the typed.js file to that folder.

    Then, in the Twine story’s JavaScript, you need to import typed.js and call the typed.js function, including any options that you would like to use:
    $(function () {
        $.getScript("http://twinerocks.com/js/typed.js", function (data, textStatus, jqxhr) {
            $('.title').typed({
                strings: [’This sentence will be typed.'],
                    typeSpeed: 0
            });
        });
    });
    
    As you can see, the HTML selector that typed.js is applying itself to in this case has the class "title." So, the HTML looks like this:
    <h1 class="title"></h1>
    
    You don’t have to actually put content in the <h1>, as the typed.js strings" will go there.

    Let me know if you need additional clarification.
  • Ok. That makes more sense. I'll give the mathml thing a try again later this week. Thank you.

  • edited May 2015
    ok... so i need to get

    <script type="text/x-mathjax-config">
    		MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
    		</script>
    
    		<script type="text/javascript"
    		src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">;
    		</script>
    
    

    into the other format.....
    $(function () {
        $.getScript(""http://cdn.mathjax.org/mathjax/latest/MathJax.js?		config=TeX-AMS-MML_HTMLorMML", function (???????{
           
            });
        });
    });
    

    Lost after the first bit......
  • edited May 2015
    Using their own "test" code in the body of the story:
    When $a \ne 0$, there are two solutions to \(ax^2 + bx + c = 0\) and they are
    $$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$
    

    …this should work:
    $(function () {
        $.getScript("https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMM", function (data, textStatus, jqxhr) {
            MathJax.Hub.Config ({
                    tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}
            });
        });
    });
    
    But it doesn’t.

    There’s most likely a conflict with Twine’s own syntax.

    I’ll try to experiment a little more later.
  • @stephenteacher Try this. Import it from the attached file to look at the Javascript and Stylesheet, and play with some passages. You will need to use special markup, indicated in comments in the Javscript section, because $ has special meaning to Twine/SugarCube.

    Caveat: I could only get this to work in SugarCube, not Harlowe, which is the default story format. SugarCube is fortunately what's used in the example file I've attached, so you can rename the story and keep importing. :) But you'll need to learn SugarCube, not Harlowe, formatting.

    SugarCube docs are here: http://www.motoslave.net/sugarcube/

    I had to play some tricks to make it work, but Javascript is halfway about tricks...
  • @timsamoff Yeah, $ is special to Twine so it conflicts with MathTex. I had to get around that by using alternate symbols, but in addition I had to reset the HTML and re-run MathTex's rendering on every passage load. Without a hook into that, it's difficult to get it to work.

    I can go into more details. :)
  • Nice work, @AvaJarvis!

    Now if we could just figure out how to split the MathJax part of this discussion into its own Forum thread… ;)
  • edited May 2015
    @AvaJarvis
    Thank you for that. I'll have a tinker.
    ....why could it not be simple........
    @timsamoff @AvaJarvis

    Thank you both for your input on this.
  • Hello everybody!

    I want to use an external javascript file which is annyang.js, ehich is used for voice recognition ,but I don´t have the link to read it from the internet. I have just a file with the code.
    Is there a way to instead of reading the file from the internet to read it from a file stored in your computer?
    $(function () {
        $.getScript("http://link.to/js/file.js", function (data, textStatus, jqxhr) {
            console.log(data); // Data returned
            console.log(textStatus); // Success
            console.log(jqxhr.status); // 200
            console.log("Typed was loaded.");
        });
    });
    

    So when you get the script instead of writing that http link, read it from a folder in your computer.

    Thank you!!
  • What version of Twine are you using?
  • Twine 2 with the default Format, Harlowe
  • Not sure...? :(
  • It is fine! Thank you anyway!

    I found the link to read it from the internet:
    $(function () {
        $.getScript("https://cdnjs.cloudflare.com/ajax/libs/annyang/1.1.0/annyang.min.js", function (data, textStatus, jqxhr) {
    
           $('someSelector').script(function(){});
        });
    			
        });
    });
    

    But I am not sure if I am doing correctly:
    If from the code I want to use this functions:
    annyang.addCommands(commands);
            annyang.start(); 
    
    What should I put in this part??
      $('someSelector').script(function(){});
    
        });
    

    Thank you!
  • Its working! thank you anyway!
  • edited June 2016
    Hello,

    Thanks to the excellent code of AvaJarvis, I was able to get MathJax working in Snowman 1.3.0

    I am new to Twine, and I am hoping to use it when teaching mathematics, making the blank background a plus. I have also adjusted the math-mode delimiters to match the standard LaTeX syntax.
    //Code to embed MathJax into Twine by AvaJarvis, posted at 
    // http://twinery.org/forum/discussion/comment/9513
    $(function () {
                    $.getScript("http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML", function(data, status, jqxhr) {
                                        MathJax.Hub.Config({ 
            TeX: {extensions: ["AMSmath.js", "AMSsymbols.js"]},     
            extensions: ["tex2jax.js"],
            jax: ["input/TeX", "output/HTML-CSS"],
            showProcessingMessages : false,
            messageStyle : "none" ,    
            showMathMenu: false ,
            tex2jax: {
                processEnvironments: true,
                inlineMath: [ ['$','$'], ['\(','\)'] ],
                displayMath: [['\[','\]'], ["\\[","\\]"] ],
                preview : "none",
                processEscapes: true
            },
            "HTML-CSS": { linebreaks: { automatic:true, width: "latex-container"} }
        });
      });
    });
    
    // Next, we tell MathJax to typset the frame 
    // 2 seconds after the link is selected by mouse or keyboard
    $(document).on("click", function () { setTimeout(function () { MathJax.Hub.Typeset()  },2) });
    $(document).on("keydown", function () { setTimeout(function () { MathJax.Hub.Typeset() },2) });
    
    

    I hope you find this useful.
  • I tried that with tracery library and I always get tracery not defined :( any help? This is the link to the library https://github.com/galaxykate/tracery

    here is the code I used:
    $(function () {
        $.getScript(" https://raw.githubusercontent.com/galaxykate/tracery/master/js/tracery.min.js", function (data, textStatus, jqxhr) {
            tracery.createGrammar({"origin": ["ahmed", "mohamed", "mostafa", "hoda"]});
      window.harlowe.variables['traceVar1'] = app.grammar.createTraceFromSymbol("origin");
    	window.harlowe.variables['traceVar2'] = app.grammar.createTraceFromSymbol("origin");
        });
    });
    
  • amidos2006 wrote: »
    I tried that with tracery library and I always get tracery not defined!
    If you look at your web-browser's Developer Console you will see why the remote script is not loading, it's because the web-server is sending it as MIME type ('text/plain') which is telling the web-browser that it is not executable.

    I tested the same script from my own local web-server using the following code and it worked fine, I had to add a delay between the file being download and the tracery object being initialised.
    var url = "http://localhost:8000/tracery.min.js";
    $(function () {
      $.getScript(url,
          function (data, textStatus, jqxhr) {
            console.log("File load was performed.");
    
            // Now you need to wait for the tracery object to be initialise.
            setTimeout(function(){
              if (window.tracery) {
                console.log("Found tracery object");
                tracery.createGrammar({"origin": ["ahmed", "mohamed", "mostafa", "hoda"]});
                /* Other code goes here.... */
              }
            }, 100);
          }
      );
    });
    
    note: I removed the window.harlowe object related code because it would first require me to include a scope escalation hack to have a window.harlowe object.
Sign In or Register to comment.