Last updated: 12 Jan 21 18:02:05 (UTC)

Keyup events in Twine (enter for buttons)

I wanted to be able to hit “Enter” to trigger buttons on every passage, but I also did NOT want to have to put an id or class on every button (because there’s one in each of 40 passages). So I used the tutorial below and here to FINALLY land on this javascript solution:

(function(){
    $(document).keyup(function(e){
        if(e.key == 'Enter'){
            $('button').trigger("click");
        }
    });
}());
(function(){
    $(document).keyup(function(e){
        if(e.key == 'Enter'){
            $('button').trigger("click");
        }
    });
}());

You can use Javascript like the following within your Story Javascript area to monitor for all keyup events that occur while the story is running.

(function () {     $(document).on(‘keyup’, function (ev) {         /* the ev variable contains a keyup event object.          * ev.key contains the key value of the key that was released.          */

/* the following shows an alert when the ‘a’ is released. */         if (ev.key === ‘a’) {             UI.alert(“the ‘a’ key was released.”);         }     }); }());

NOTE: to use https://keycode.info/====, change “ev.key === ‘a’ ” to “ev.keycode== === 13” (e.g. - 13 is the enter key).==

What you do within that monitoring code is up to you, the following are some examples:

/* the following changes to the Next passage when the ‘b’ is released. */ if (ev.key === ‘b’) {     Engine.play(“Next”); }

/* the following clicks on a link with the ID of continue when the ‘c’ is released. */

if (ev.key === ‘c’) {     $(‘a#continue’).click(); }

… the above click example assumes that your Passage contains an anchor element with an ID attribute and a  HTML attributes like so.

Continue