Last updated: 22 May 21 00:45:58 (UTC)

Twine: Textareas textboxes with word counts

See code below.

Important notes:

  • Have to create arrays for the string variables. I.e., the author bio ($bio) is “I come from Australia”. To count this variable:
    • <<set $bioArray to $bio.split(“ “)>> // splits on the spaces
    • $bioArray.length then will return a number = word count (4 here)

Variations:

  • If the word count limit might vary according to another variable.
    • So, the collaborator bios were 100 words each, but I didn’t know how many collaborators each might have. So they enter collaborators as a comma-separated list (which I then set into an array as above), and I can use the length property of that array to multiply by the 100-word limit, to get the overall limit for the box.
    • I didn’t stop them entering more words, just turned the word count red when it did, and set conditions on the submission button that told them to correct the word count, or it wouldn’t submit.

Word Count: 0 <><> postdisplay[‘read-crBioID’] = function (t) {     $(‘#crBioID’).on(‘keyup’, function () {         // Get the input text value         var words = document.getElementById(“crBioID”).value;         State.variables.crBio = words; // Sets the Twine variable         var mult = state.active.variables.collab.length; //         var limit = 100 * mult;         // Initialize the word counter         var count = 0;

// Split the words on each space character         var split = words.split(’ ');

// Loop through the words and increase the counter when         // each split word is not empty             for (var i = 0; i < split.length; i++) {                 if (split[i] != “”) {                     count += 1;                 }             }

// Display it as output         if (count > 100 or limit) {             ('#showcrBio').css('color', 'red');             document.getElementById("showcrBio").innerHTML = count;         } else {             KaTeX parse error: Expected 'EOF', got '#' at position 3: ('#̲showcrBio').css…(‘#showcrBio’).css(‘color’, ‘green’);             document.getElementById(“showcrBio”).innerHTML = count;         }

}); }; <> <>