LodeStarScript v2

Table of Contents

Introduction
About Scripting Languages
About the Script Editor
About the LodeStarScript Language
Expression Operators
About Functions
Branching Functions
Property Changing Functions
Data Functions
Drag Functions
Interactivity Functions
Math Functions
Media Functions
String Functions
SCORM Functions
CMI5/XAPI Functions
Utility Functions
By Alphabet

Introduction

In LodeStar 10, LodeStarScript is expanded. Before using any of the functions listed below, please learn about the scripting language and how to access the script editor. Download LodeStar 10. To learn what version you are using, select Help > About in the app.

About Scripting Languages

A scripting language gives you the power to do things in response to student-generated events such as showing a page, clicking on an image, answering a question correctly or incorrectly, and dragging an item.

But what can you do with a scripting language? In a nutshell, you can store information in variables, arrays and sets. You can make decisions. And you can execute functions to branch to different parts of a project or change the properties of a graphic, to cite two examples.

The LodeStar script is a pared down version of JavaScript, a popular scripting language. In addition to JavaScript, LodeStar offers specialized functions that perform various tasks. Those functions are documented below. The goToNextPage() function, for example, causes the project to jump to the next page.

For those who know a little about scripting, the LodeStar script lets you do this:

var score = getValue("score");
if(score > .8){
   jumpToPage("Enrichment")
}else{
   goToNextPage();
}

but not this:

var element = document.createElement("div")
element.id = 'output';

In other words, LodeStar does not allow the creation or the direct manipulation of HTML DOM elements. The LodeStar script is a subset of JavaScript plus a long list of specialized functions.

About the Script Editor

Scripts are created or edited in a script editor. LodeStar offers two levels of script editor. The first level is simply a text box used to write and store the script. The deeper level offers a full featured script editor that checks for errors.

The LodeStar Script editor can be accessed by the author clicking on any Branch icon, selecting Execute Command, and selecting “Edit”.

Branch Icon
LodeStar Script Editor. Click on a Branch Icon, select Execute Command(s) and then click on the ‘Edit’ button.

The Script Editor catches syntax errors and misnamed functions. It offers a ‘Test’ button to check your code. (Please note: For security reasons, use the copy and paste buttons to perform copy and paste operations.)

About the LodeStar Scripting Language

LodeStar script is a lot like JavaScript but it has its own library of functions and, for security reasons, restricts direct access to the document object model of the page. In other words, changes to such elements as image elements is supported by a specialized LodeStar function.

So, like Javascript you can write a statement such as this:

var myVar = 1;

This declares a local variable called myVar and assigns the value of 1 to the variable.

To store the value to longer term memory, you should use a LodeStar function:

var myVar = 1;
setValue("score", myVar);

To retrieve this value from longer term memory, use the following:

var myScore = getValue("score");

Expression Operators

LodeStar script operators are similar to JavaScript operators

+ add
- subtract
* multiply
/ divide
% modulo
== equality check
=== strict equality check
!== not equals
& and
| or
<= less than or equals to
>= greater than or equals to
< less than
> greater than
in property in object
instanceof the instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object

About Functions

In short, the syntax and language are javaScript-like, but the functions (e.g. getValue) are specific to the LodeStar Scripting language.

Here is a listing and explanation of functions by category. The term program is used to describe the project from a programming perspective. Branching functions, for example, change the ‘flow’ of the program. If a student performs poorly on a set of questions, the program flow might get diverted to a remedial section of the project. (Note that this can be done with the ‘Gate’ page type or a script function.)

Functions (By Category)

Branching Functions

goToNextPage();
Causes the program to jump to the next page, if available.

goToPreviousPage();
Causes the program to jump to the preceding page, if available.

jumpToPage(‘Page ID’);
Causes the program to jump to a specified page. Specify pages by page ID or the specific unique identifier number that is assigned to each page. You can get a ‘page’s unique ID by clicking on the help icon for that page. See picture. A unique id is usually a 13 digit number that looks like this: 1567384615584

Help Icon, which will give you the 13 digit unique id for the current page.

openUrl(url);
Causes a web page to display in a pop-up window, where url is a valid absolute or relative address. Absolute addresses should used the https secure protocol.

getCurrentUID()
Retrieves the current page’s unique 13 digit number. Think of it as a pages social security number.

Property Changing Functions

changeColor(id, hexNumber)
Changes the color of an HTML element, where id is element ID (no hashtag) and hexNumber is a color value in the form of #FF00FF or a color name like ‘green’. Every image and every SVG graphic has a unique element ID.

Example:
changeColor(“1627433384892”, “green”);

changeColor(“1627433384892”, “#00FF00”);


changeImage(currentImage, newImage)
swaps current image with a new image, where currentImage is the element ID of the image that will change, and newImage is the element ID of the replacing image. This function will not change the image ID.

In the screenshot below, notice the ID for the trash can image. If this image were replaced by another image by the changeImage function, the ID would remain unchanged.

Screenshot of image Dialog

changeOpacity(id, 0 – 1);
changes the opacity of an element such as an image or SVG graphic, where id is the element ID and the second value is a number between 0 and 1.

changePosition(id, 0 – 1, axis);

Please Note: we recommend using this function on SVG elements only. The function
changes the position of an SVG element, where id is element ID (no hashtag), 0 to 1 is a percentage along the axis of an invisible hTrack or vTrack and axis is either ‘x’ or ‘y’

We also highly recommend upgrading to LodeStar 10 Build 16 or later. This function was updated in build 16 to provide more flexibility.

An SVG element must have a defined property set before this function is used. If changing the position of an SVG element along the x axis, then the property of hTrackLength must be set. If changing the position on the y axis, then the property of vTrackLength must be set. Here is how:

setProp(id, "hTrackLength", "200");

Example:

setProp("ball", "hTrackLength", "570");
changePosition("ball", .5, "x");

In the above example, ball is the element ID of an SVG graphic. hTrackLength is a property name that describes an invisible horizontal track that has been assigned a length of 570 pixels.

Please note: The point of origin (0,0) is the original position of the element. In the diagram below the ball (black circle) is constrained to a track (gray rect) on the x axis. When dragged, the ball will stay on the track. The ball was placed in the middle of the track and assigned an hTrackLength of 500. changePosition(“ball, 1, “x) will place the ball at the end of the track 500 pixels from the center. changePosition(“ball”, 0, “x”) will place the ball in the center. changePosition (“ball”, -.5, “x”) places the ball 1/4 of the way down the 1000 wide track. changePosition(“ball”, -1, “x”) places the ball at the start of the track.

hTrackLength is set to 500.

If the ball were not assigned an hTrackLength, then the hTrackLength will be set to the width of the SVG viewBox. In this case the viewBox is 1000 pixels wide. If the ball were set in the center, a changePosition of 1 will move the ball 500 pixels to the right of the screen. A value of .5 places the ball on the right edge of the track. (It is therefore a good idea to set the hTrackLength property.)

The easiest way to move a ball along a track is to set the ball at the very start of the track and set the hTrackLength property to length of the track. The same would apply to vertical tracks. Currently, LodeStar only supports horizontal and vertical tracks and not diagonal or path-based tracks.

For non-SVG images and divs, changePosition changes the positioning of the element to absolute positioning (removing from the flow of the page) and then positions the element a set percentage from the left or top of the page depending on the axis. The initial change from relative to absolute positioning may surprise the author. For example, an image might be originally positioned in between paragraphs. changePosition will cause the position to be removed from that flow and absolutely positioned according to the values in changePosition. 

changeRotation(id, degrees, x, y);
changes the rotation of an element, where id is element ID (no hashtag), degrees is the angle of rotation expressed in degrees, and x and y are the coordinates for the point of rotation (anchor point) expressed in percentage of the canvas. Use whole numbers.

Example:

changeRotation("triangle", 90, 50, 50);

In the example, “triangle” is the element id of an SVG path, 90 is the degree of rotation, and 50 is the half-way point on the x axis of the parent of the triangle, which, in this case, is the SVG canvas. The second 50 is the half-way point on the y axis.

changeText(id, value);
changes the text content of an element, where id is element ID (no hashtag) and value is the text. You can assign ids to SVG text, TextLayoutWidget elements, and HTML elements that you manually insert into the page.

preventPageHide(id, value, left, top, zIndex, captureClicks);
causes a page to become visible and overlay on top of the current page, where id is element ID (no hashtag), value is true or false, left is percentage of viewer to reposition left edge of page, top is percentage of viewer to reposition top edge of page, zIndex is page position on the z axis, and captureClicks is whether or not element will receive mouse or touch clicks.

Example:

preventPageHide("question", true, 10, 40, 100, "true");

Note that “true” requires quotation marks, if the author intends for this overlay to capture touch events or mouse clicks.

show(id);
displays an element, where id is the id of the element

Example:

show("ball_1");

hide(id);
hides an element, where id is the id of the element

Example:

hide("ball_1");

getPosition(id);
returns position of element, where id is the id of the element

Example:

var position = getPosition("ball_1");
//use position.left and position.top

Data Functions


setProp(id, name, value);
associates a property name and value to a specific id, where id is element ID (no hashtag) and name is a property name such as xPos or yPos and value is a value to store in the property.

Please note: setProp doesn’t actually change the physical property of an element. It simply stores properties related to an element. Again, setProp does not change the property. Use functions beginning with ‘change’, such as changeOpacity() to change properties. Use setProp to remember values related to an element. Properties can be arbitrary The only property names that have special significance are xPos, yPos, hTrackLength, yTrackLength.

setValue(‘variable name’, value);
stores the value of a variable. When a variable is declared within a script, its scope (life) is restricted to that script. Once the script finishes executing, the variable is removed from memory. To persist a variable and its value across multiple pages, use setValue().

To persist a variable across sessions, use suspendData() and do not set the completion status to “complete”. Learning Management Systems delete suspended data once the completion status of a learner has been set to complete.

appendValue(‘variable name’, value);
adds a new value to whatever was previously stored.

So if you scripted the following, output would equal 5.

setValue("score", 3);
appendValue("score", 2);
var output = getValue("score");

getValue(‘variable name’);
retrieves the value of a stored variable. See appendValue for an example.

addToSet(set, item);
adds an item to a set, where set is name of a set of items and item is the thing to be added. The item cannot start with a number.

A set is guaranteed not to have duplicate items.

removeFromSet(set, item);
removes an item from a set, where set is name of a set of items and item is the thing to be added. A set is guaranteed not to have duplicate items.


setContains(set, item or comma separated items);
returns true if set contains an item, where set is the name of a set, and item is what you are looking for.

addToQueue(name,value,isVIQ,position);
getQueue(name);
these functions are currently deprecated


addToArray(name,value);|
adds an item to an array(list), where name is the name of the array and value is the item to be added to the array

when adding an object to an array, the object must be in this form:

var s1 = {problem: “1”, text:”problem 1″, tech_1: “c4.mp4”, tech_2: “g4.mp4”};
addToArray(“scenarios”, s1);

When adding an object, do not place the property names in quotes.

When reading the array, follow this convention:

var array = getArray(“scenarios”);
var scenario = array[0];
var tech_1 = scenario[“tech_1”];


getArray(name);
returns a comma separated list of all the items in the array, where name is the name of the array.

updatevariablewidget(id);
updates EmbeddedVariable Widget without a page refresh, where id is ID (no hashtag) of EmbeddedVariable widget.

To use the updateVariableWidget function, embed a variable in the widget, such as myVar.

{myVar}

Then set the value of myVar, with the following:

setValue(“myVar”, “xyz”);

Then update the widget with the id of the widget.

Example:

setValue("myVar", "xyz");
updatevariablewidget("w1");

Please note: if you do not explicitly update the variable widget, it hangs on to the old value of myVar. Therefore, update the variable, and then update the variable widget.

isNumber(value);
returns true if value is a number

Drag Functions

isOverlap(element1ByID, element2ByID);
returns true if element 1 overlaps element 2


enableDraggable(elementByID);
enables dragging only an elements set up to be draggable


disableDraggable(elementByID);
disables dragging only an elements set up to be draggable

Interactivity Functions

resetPage();
resets the current page. Use together with jumpToPage(“pageID”) in order to refresh the page.

resetPageByID(ID);
resets page by ID. Use 13 digit ID (UID). Use together with jumpToPage(“pageID”) in order to refresh the page.

resetAllInteractivity();
resets all pages with locked questions

getUserScore()
returns the system’s user score (same value used on report page)

getTotalScore()
returns the system’s total score (same value used on report page)

setCustomUserScore(value);

overrides LodeStar’s default behavior by setting the user score. Authors can keep track of their own scoring variables and then set both the user score and the total score with the matching functions.

setCustomTotalScore(value);

overrides LodeStar’s default behavior by setting the total possible score. Authors can keep track of their own scoring variables and then set both the user score and the total score with the matching functions

executePageBranch(‘Page ID’)

executes the page level branch options of a page, where Page ID is the unique identifier number assigned to the page.

Math Functions

All of the Javascript Math functions are supported. For convenience, several math functions permit you to drop the Math object. Starting with LodeStar 10 Build 16, you can use Math.random() or random().

Math.random() or random();
returns a number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range.

Math.round(value);
rounds the number passed as parameter to its nearest integer (whole number)
Math.round(12.5) rounds to 12, Math.round(12.51) rounds to 13


Math.floor(value) or floor(value);
returns the largest integer less than or equal to a given number.

Math.ceil(value) or ceil(value);
returns the smallest integer greater than or equal to a given number.

Math.pow(value, power) or pow();
returns the value raised to the power.

Math.round(value);
rounds a value to the nearest integer

Math.sqrt(value) or sqrt(value)
returns square root of value.

Media Functions

animate(id, object, duration)
animates the element’s css properties, where id is element ID (no hashtag),object is a javascript object in the form of {property:value}, and duration is the length of the animation in milliseconds.

Note: pay particular attention to how the quotes are used in this example.

var jsObject = '{"opacity": ".5","bottom":"10%"}';
animate("star", jsObject, 10000);

animatePosition(id, startLeft, startTop, endLeft, endTop, duration)
animates the element’s left and top properties, where id is element ID (no hashtag),startLeft is the initial value for the css property left, startTop is the initial top position, endLeft and endTop are the final positions, and duration is the length of the animation;

animateOpacity(id, opacity, duration)
animates the element’s opacity property, where id is element ID (no hashtag), opacity is an opacity value between 0 and 1, and duration is the length of the animation.

updateAnimation(uid, state (optional), currentTime (optional), duration (optional), iterations (optional), playbackRate (optional), onFinish (optional))
Available in LodeStar 10 (Beta 3)
Updates a page’s animation, where id is the page ID; state is play, pause, or reverse; currentTime is the start time in seconds; duration is the length of the animation time in seconds; iterations is the number of animation repeats; playbackrate is normally 1 but can be 2 for twice the playback rate or a higher number; onFinish is the page ID of the page that holds the branchoptions for when the animation finishes.

Important Note: the iterations parameter in updateAnimation can be a fraction. For example, let’s assume in the following code userScore is assigned 5 and totalScore is assigned 10. The percentage would therefore equal .5. That value will be assigned to interations. The animation will advance from the start to midway through the animation. This can be used creatively when animating a meter that indicates the user score. The animation can start with the meter at 0 percent and end at 100 percent. An iterations value of .5 would advance the animation to its midway point.

Here is an example:

var percentage = userScore/totalScore;
var iterationStart = 0;
var iterations = Math.max(0.1, percentage);

updateAnimation(“1683657484792”, “play”, “0”, “2”, iterations, “1”, iterationStart);

webanimate(elementid, timelineid, duration (optional), direction (optional), currentTime (optional), position (optional), callBack (optional))
animates the element’s css properties based on a timeline creating with the animation editor, where id is element ID (no hashtag), timelineid is the id of an existing timeline created in the editor, duration is the length of the animation in seconds, currentTime is where to start the animation in seconds, position is the css position property which is usually set to ‘absolute’ to support top and left movement, and callBack is the name of a page whose branch options will be called when animation finishes.

webanimate("star", "starMovement", 10);

webanimate("star", "starMovement", 10, "normal", 0, "absolute");

playAudio(filename);
plays an audio that is preloaded to LodeStar. The audio file, for example, can be loaded into a page that is removed from the flow. Only the filename is needed to reference the file and not the full path to the file.

playAudio("sample.mp3");


pauseAudio();
stops all audio files that are playing. pauseAudio is a misnomer. The function stops audio.

String (Text) Functions

concatenate(val1,val2);
appends val2 to val1

var myString = concatenate("apple ", "pie");

In the example, myString would be assigned the value of “apple pie”;

getValueAsString(value);
converts value to a string of characters

getValueAsNumber(value);
converts value to a number

SCORM Functions

suspendData();
writes all values placed in storage by setValue() to a storage area in the learning management system named suspend_data. The contents of suspend_data are emptied once the learning object sets the completion status to ‘completed’.

In SCORM 2004 data model, learner’s progress is captured by two data elements, cmi.completion_status (completed vs incomplete) and cmi.success_status (passed vs failed). Once cmi.completion.status is marked as ‘completed’, suspend_data is emptied.

retrieveData();
retrieves the data that is kept in the learning management system’s suspend_data (See suspendData()).


clearData();
clears all values placed in storage by setValue();

retrieveData(successPage, failPage);
retrieves the data that is kept in the learning management system’s suspend_data , where successPage is the page title of the jumpto page if data successfully retrieved and failPage is the page title of the jumpto page if data retrieval fails

setCompletionStatus();
sets the completion status that will be reported to the learning management system. Valid values include “completed”, “incomplete”, “not attempted”, and “unknown”.

CMI5/XAPI Functions (requires ActivityMaker V9 Build 16+)

sendXAPIStatement(verb, object)

sends xAPI statement to Learner Record Store where verb is action (e.g. ‘experienced’) and object is the object of the experience when project is exported as CMI5.

Utility Functions

getDay();
returns day of month as a number.

getMonth();
returns month as a number.

getYear()
returns year as a number.

addOverlay(‘Page ID’);
overlays the page in a window popup. Use the page’s page id that is typed in the page ID field rather than the 13 digit number.

message(value);
pops up a message, where value is the message

showToolTip(message, xpos, ypos);
shows a tooltip with message at x and y position

hideToolTip();
hides tooltip

removeFromFlow();
removes the current page from the flow (which means that the learner can no longer navigate to the page with the next and back buttons).

removeFromResources(‘Page ID’);
removes the page that was made available as a resource on the screen


removeFromFlowById(‘Page ID’);
removes the page identified by ‘page id’ from the flow (which means that the learner can no longer navigate to the page with the next and back buttons)

restoreToFlowByID(‘Page ID’)
restores page matching page ID to the flow

updateProgressBar(value, max);
manually takes control of the progress bar, where value is the current position of the progressbar and max is its maximum value.

addToResources(‘Page ID’);
makes the page available upon the click of a button on the screen.

removeFromResources(‘Page ID’);
removes the page that was made available as a resource on the screen

showAsLayer(‘Page ID’,value,left, top, zIndex, captureClicks)
shows the page as a layer that is absolutely positioned, where PageID is either a UID or page id and where value is either true or false. A value of true means to show the page; a value of false hides the page. A value of ‘show once’ shows the page as layer only once. Left is the percentage from the left of the left corner of the page. Top is the percentage from the top of the top corner of the page. zIndex is the vertical stacking order of the page. The higher the number, the further to the front. Set CaptureClicks to true to capture and process mouse clicks and touch events. Use only on Text Pages.

updateGadget();
updates a gadget, if gadgets are used in the project. Gadgets is an advanced concept (as opposed to widgets).


By Alphabet

addOverlay(‘Page ID’);
overlays the page in a window popup. Use the page’s page id that is typed in the page ID field rather than the 13 digit number.


addToArray(name,value);|
adds an item to an array(list), where name is the name of the array and value is the item to be added to the array

when adding an object to an array, the object must be in this form:

var s1 = {problem: "1", text:"problem 1", tech_1: "c4.mp4", tech_2: "g4.mp4"};
addToArray("scenarios", s1);

When adding an object, do not place the property names in quotes.

When reading the array, follow this convention:

var array = getArray("scenarios");
var scenario = array[0];
var tech_1 = scenario["tech_1"];

addToResources(‘Page ID’);
makes the page available upon the click of a button on the screen.

addToSet(set, item);
adds an item to a set, where set is name of a set of items and item is the thing to be added. The item cannot start with a number.

A set is guaranteed not to have duplicate items.

animate(id, object, duration)
animates the element’s css properties, where id is element ID (no hashtag),object is a javascript object in the form of {property:value}, and duration is the length of the animation in milliseconds.

Note: pay particular attention to how the quotes are used in this example.

var jsObject = '{"opacity": ".5","bottom":"10%"}'; 
animate("star", jsObject, 10000);

animatePosition(id, startLeft, startTop, endLeft, endTop, duration)
animates the element’s left and top properties, where id is element ID (no hashtag),startLeft is the initial value for the css property left, startTop is the initial top position, endLeft and endTop are the final positions, and duration is the length of the animation;

animateOpacity(id, opacity, duration)
animates the element’s opacity property, where id is element ID (no hashtag), opacity is an opacity value between 0 and 1, and duration is the length of the animation.

appendValue(‘variable name’, value);
adds a new value to whatever was previously stored.

So if you scripted the following, output would equal 5.

setValue("score", 3);
appendValue("score", 2);
var output = getValue("score");

changeColor(id, hexNumber)
Changes the color of an HTML element, where id is element ID (no hashtag) and hexNumber is a color value in the form of #FF00FF or a color name like ‘green’. Every image and every SVG graphic has a unique element ID.

Example:
changeColor(“1627433384892”, “green”);

changeColor(“1627433384892”, “#00FF00”);


changeImage(currentImage, newImage)
swaps current image with a new image, where currentImage is the element ID of the image that will change, and newImage is the element ID of the replacing image. This function will not change the image ID.

changeOpacity(id, 0 – 1);
changes the opacity of an element such as an image or SVG graphic, where id is the element ID and the second value is a number between 0 and 1.

changePosition(id, 0 – 1, axis);

Please Note: we recommend using this function on SVG elements only. The function
changes the position of an SVG element, where id is element ID (no hashtag), 0 to 1 is a percentage along the axis of an invisible hTrack or vTrack and axis is either ‘x’ or ‘y’

We also highly recommend upgrading to LodeStar 10 Build 16 or later. This function was updated in build 16 to provide more flexibility.

An SVG element must have a defined property set before this function is used. If changing the position of an SVG element along the x axis, then the property of hTrackLength must be set. If changing the position on the y axis, then the property of vTrackLength must be set. Here is how:

setProp(id, "hTrackLength", "200");

Example:

setProp("ball", "hTrackLength", "570");
changePosition("ball", .5, "x");

In the above example, ball is the element ID of an SVG graphic. hTrackLength is a property name that describes an invisible horizontal track that has been assigned a length of 570 pixels.

Please note: The point of origin (0,0) is the original position of the element. In the diagram below the ball (black circle) is constrained to a track (gray rect) on the x axis. When dragged, the ball will stay on the track. The ball was placed in the middle of the track and assigned an hTrackLength of 500. changePosition(“ball, 1, “x) will place the ball at the end of the track 500 pixels from the center. changePosition(“ball”, 0, “x”) will place the ball in the center. changePosition (“ball”, -.5, “x”) places the ball 1/4 of the way down the 1000 wide track. changePosition(“ball”, -1, “x”) places the ball at the start of the track.

hTrackLength is set to 500.

If the ball were not assigned an hTrackLength, then the hTrackLength will be set to the width of the SVG viewBox. In this case the viewBox is 1000 pixels wide. If the ball were set in the center, a changePosition of 1 will move the ball 500 pixels to the right of the screen. A value of .5 places the ball on the right edge of the track. (It is therefore a good idea to set the hTrackLength property.)

The easiest way to move a ball along a track is to set the ball at the very start of the track and set the hTrackLength property to length of the track. The same would apply to vertical tracks. Currently, LodeStar only supports horizontal and vertical tracks and not diagonal or path-based tracks.

For non-SVG images and divs, changePosition changes the positioning of the element to absolute positioning (removing from the flow of the page) and then positions the element a set percentage from the left or top of the page depending on the axis. The initial change from relative to absolute positioning may surprise the author. For example, an image might be originally positioned in between paragraphs. changePosition will cause the position to be removed from that flow and absolutely positioned according to the values in changePosition. 

changeRotation(id, degrees, x, y);
changes the rotation of an element, where id is element ID (no hashtag), degrees is the angle of rotation expressed in degrees, and x and y are the coordinates for the point of rotation (anchor point) expressed in percentage of the canvas. Use whole numbers.

Example:

changeRotation("triangle", 90, 50, 50);

In the example, “triangle” is the element id of an SVG path, 90 is the degree of rotation, and 50 is the half-way point on the x axis of the parent of the triangle, which, in this case, is the SVG canvas. The second 50 is the half-way point on the y axis.

changeText(id, value);
changes the text content of an element, where id is element ID (no hashtag) and value is the text. You can assign ids to SVG text, TextLayoutWidget elements, and HTML elements that you manually insert into the page.


clearData();
clears all values placed in storage by setValue();

concatenate(val1,val2);
appends val2 to val1

var myString = concatenate("apple ", "pie");

In the example, myString would be assigned the value of “apple pie”;


disableDraggable(elementByID);
disables dragging only an elements set up to be draggable


enableDraggable(elementByID);
enables dragging only an elements set up to be draggable

executePageBranch(‘Page ID’)
executes the page level branch options of a page, where Page ID is the unique identifier number assigned to the page.


getArray(name);
returns a comma separated list of all the items in the array, where name is the name of the array.

getCurrentUID()
Retrieves the current page’s unique 13 digit number. Think of it as a pages social security number.

getDay();
returns day of month as a number.

getMonth();
returns month as a number

getPosition(id);
returns position of element, where id is the id of the element

Example:

var position = getPosition("ball_1");
//use position.left and position.top

getTotalScore()
returns the system’s total score (same value used on report page)

getUserScore()
returns the system’s user score (same value used on report page)

getValue(‘variable name’);
retrieves the value of a stored variable. See appendValue for an example.

getValueAsNumber(value);
converts value to a number

getValueAsString(value);
converts value to a string of characters

getYear();
returns year as a number

goToNextPage();
Causes the program to jump to the next page, if available.

goToPreviousPage();
Causes the program to jump to the preceding page, if available.

hide(id);
hides an element, where id is the id of the element

hideToolTip();
hides tooltip

isNumber(value);
returns true if value is a number

isOverlap(element1ByID, element2ByID);
returns true if element 1 overlaps element 2

jumpToPage(‘Page ID’);
Causes the program to jump to a specified page. Specify pages by page ID or the specific unique identifier number that is assigned to each page. You can get a ‘page’s unique ID by clicking on the help icon for that page.

Math.ceil(value);
returns the smallest integer greater than or equal to a given number.


Math.floor(value);
returns the largest integer less than or equal to a given number.

Math.random();
returns a number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range.

Math.round(value);
rounds the number passed as parameter to its nearest integer (whole number)
Math.round(12.5) rounds to 12, Math.round(12.51) rounds to 13

Math.round(value);
rounds a value to the nearest integer

message(value);
pops up a message, where value is the message

openUrl(url);
Causes a web page to display in a pop-up window, where url is a valid absolute or relative address. Absolute addresses should used the https secure protocol.


pauseAudio();
stops all audio files that are playing. pauseAudio is a misnomer. The function stops audio.

playAudio(filename);
plays an audio that is preloaded to LodeStar. The audio file, for example, can be loaded into a page that is removed from the flow. Only the filename is needed to reference the file and not the full path to the file.

playAudio("sample.mp3");

preventPageHide(id, value, left, top, zIndex, captureClicks);
causes a page to become visible and overlay on top of the current page, where id is element ID (no hashtag), value is true or false, left is percentage of viewer to reposition left edge of page, top is percentage of viewer to reposition top edge of page, zIndex is page position on the z axis, and captureClicks is whether or not element will receive mouse or touch clicks.

Example:

preventPageHide("question", true, 10, 40, 100, "true");

removeAllResources()
removes all resources

retrieveData(successPage, failPage);
retrieves the data that is kept in the learning management system’s suspend_data , where successPage is the page title of the jumpto page if data successfully retrieved and failPage is the page title of the jumpto page if data retrieval fails

removeFromFlow();
removes the current page from the flow (which means that the learner can no longer navigate to the page with the next and back buttons).


removeFromFlowById(‘Page ID’);
removes the page identified by ‘page id’ from the flow (which means that the learner can no longer navigate to the page with the next and back buttons)

removeFromSet(set, item);
removes an item from a set, where set is name of a set of items and item is the thing to be added. A set is guaranteed not to have duplicate items.

removeFromResources(“pageID”)
removes page matching pageID from resources

resetPage();
resets the current page. Use together with jumpToPage(“pageID”) in order to refresh the page.

resetPageByID(ID);
resets page by ID. Use 13 digit ID (UID). Use together with jumpToPage(“pageID”) in order to refresh the page.

resetAllInteractivity();
resets all pages with locked questions

restoreToFlowByID(‘Page ID’)
restores page matching page ID to the flow

retrieveData();
retrieves the data that is kept in the learning management system’s suspend_data (See suspendData()).

setCompletionStatus();
sets the completion status that will be reported to the learning management system. Valid values include “completed”, “incomplete”, “not attempted”, and “unknown”.

sendXAPIStatement(verb, object)

sends xAPI statement to Learner Record Store where verb is action (e.g. ‘experienced’) and object is the object of the experience when project is exported as CMI5.


setContains(set, item or comma separated items);
returns true if set contains an item, where set is the name of a set, and item is what you are looking for.

setCustomUserScore(value);

overrides LodeStar’s default behavior by setting the user score. Authors can keep track of their own scoring variables and then set both the user score and the total score with the matching functions.


setProp(id, name, value);
associates a property name and value to a specific id, where id is element ID (no hashtag) and name is a property name such as xPos or yPos and value is a value to store in the property.

Please note: setProp doesn’t actually change the physical property of an element. It simply stores properties related to an element. Again, setProp does not change the property. Use functions beginning with ‘change’, such as changeOpacity() to change properties. Use setProp to remember values related to an element. Properties can be arbitrary The only property names that have special significance are xPos, yPos, hTrackLength, yTrackLength.

setValue(‘variable name’, value);
stores the value of a variable. When a variable is declared within a script, its scope (life) is restricted to that script. Once the script finishes executing, the variable is removed from memory. To persist a variable and its value across multiple pages, use setValue().

To persist a variable across sessions, use suspendData() and do not set the completion status to “complete”. Learning Management Systems delete suspended data once the completion status of a learner has been set to complete.

setCustomTotalScore(value);

overrides LodeStar’s default behavior by setting the total possible score. Authors can keep track of their own scoring variables and then set both the user score and the total score with the matching functions

suspendData();
writes all values placed in storage by setValue() to a storage area in the learning management system named suspend_data. The contents of suspend_data are emptied once the learning object sets the completion status to ‘completed’.

In SCORM 2004 data model, learner’s progress is captured by two data elements, cmi.completion_status (completed vs incomplete) and cmi.success_status (passed vs failed). Once cmi.completion.status is marked as ‘completed’, suspend_data is emptied.

show(id);
displays an element, where id is the id of the element

showAsLayer(‘Page ID’,value,left, top, zIndex, captureClicks)
shows the page as a layer that is absolutely positioned, where PageID is either a UID or page id and where value is either true or false. A value of true means to show the page; a value of false hides the page. A value of ‘show once’ shows the page as layer only once. Left is the percentage from the left of the left corner of the page. Top is the percentage from the top of the top corner of the page. zIndex is the vertical stacking order of the page. The higher the number, the further to the front. Set CaptureClicks to true to capture and process mouse clicks and touch events. Note that “true” requires quotation marks, if the author intends for this overlay to capture touch events or mouse clicks. Use only on Text Pages.

showToolTip(message, xpos, ypos);
shows a tooltip with message at x and y position.

updateAnimation(uid, state (optional), currentTime (optional), duration (optional), iterations (optional), playbackRate (optional), onFinish (optional))
Available in LodeStar 10 (Beta 3)
Updates a page’s animation, where id is the page ID; state is play, pause, or reverse; currentTime is the start time in seconds; duration is the length of the animation time in seconds; iterations is the number of animation repeats; playbackrate is normally 1 but can be 2 for twice the playback rate or a higher number; onFinish is the page ID of the page that holds the branchoptions for when the animation finishes.

updateProgressBar(value, max);
manually takes control of the progress bar, where value is the current position of the progressbar and max is its maximum value.

updateGadget();
updates a gadget, if gadgets are used in the project. Gadgets is an advanced concept (as opposed to widgets).

updatevariablewidget(id);
updates EmbeddedVariable Widget without a page refresh, where id is ID (no hashtag) of EmbeddedVariable widget.

Example:

setValue("myVar", "xyz");
updatevariablewidget("w1");

webanimate(elementid, timelineid, duration (optional), direction (optional), currentTime (optional), position (optional), callBack (optional))

animates the element’s css properties based on a timeline creating with the animation editor, where id is element ID (no hashtag), timelineid is the id of an existing timeline created in the editor, duration is the length of the animation in seconds, currentTime is where to start the animation in seconds, position is the css position property which is usually set to ‘absolute’ to support top and left movement, and callBack is the name of a page whose branch options will be called when animation finishes.

Making your projects interactive and interesting with a little bit of code

Introduction:

Instructional designers, instructors and trainers who want their eLearning to go beyond presentation might consider acquiring a new skill:  basic coding.  Learning a little code will help you track learners, adapt to their performance, change the direction of the activity, visualize learner’s performance and so much more.  You don’t need to become a computer scientist or even a computer programmer.  You need to learn a few skills that are on the same level of complexity as the Excel spreadsheet formula language.  You need to learn about variables, functions, and conditional statements.  This project will help you learn those skills.

The objective of this lesson is to create a working traffic light. When the learner clicks a button the traffic light will change. This project makes use of variables, functions, and conditional logic.  You will be able to apply these basic principles to your own projects.  We chose traffic lights because you will easily recognize when you have got it right.  We also introduce the power of SVG graphics in this tutorial.  You will learn more about them. 

Before we begin, a note about the step-by-step instructions:  First, I use the words ‘code’ and ‘script’ interchangeably.  Secondly, when we get to writing code, I’ll display the line of code and provide a detailed explanation of what it does. That is as important as the line of code.

So, let’s get started. If you would rather watch me create this project first and then attempt it, go to this link:

LodeStar 9 — Elements Of Interactivity – YouTube

 Download the most recent version of LodeStar

The instructions in this DIY tutorial work on LodeStar 9 build 7b or greater. This build was released on April 10th, 2021.

You can download the latest release from https://lodestarlearning.com/.

Select the ActivityMaker template:

ActivityMaker is a great place to start.  It has everything we need.    

  1. Select the ActivityMaker template.  (The first template).
  2. Click on ‘Create Project’ and title your project.  Call it Traffic Light Demo.

Create the first two pages

  1. Once the project opens, click on the HTML Editor and create a title page.  Give the page a page ID of ‘Intro’.  Page Id’s are important when we use branching logic.  Each page has a unique identifier that the program code understands.  The Page ID also gives the page a human-friendly name.
  2. Click on the + button at the bottom to add a new page to the project.
  3. Page forward to page two.  Notice that page two is the same page type as page one.  That works for this project.  Give page two the Page ID of “Traffic lights”.

 

Bitmap Graphics and Vector Graphics

We will be using bitmaps and vectors. Let’s learn about them. Bitmap or raster images are created with a collection of bits or pixels. They are spreadsheets of color values and they can’t be scaled up without loss.  Vector graphics are shapes with properties like fill color, stroke width and placement that are modified by mathematical formulas. They can be scaled up without loss of clarity.  It is very difficult programmatically to address a part of a bitmap image (a tree for example) and change its properties.  On the other hand, some types of vector graphics are composed of elements that can be targeted in much the same way as an HTML element (a part of a web page). We’ll see what that means in the traffic light demo.

 

Create the SVG

SVG is an acronym for Scalable Vector Graphic. It is a type of vector graphic that is supported by most modern browsers.  SVG includes the language to define shapes such as paths and outlines consisting of straight lines and curves, bitmap images, and text. Computer commands use this information to draw the objects to the screen at any scale.  An SVG path element looks sharp whether displayed on a smartphone or a Jumbotron.  SVG Elements (parts of the drawing) can be grouped, and styled.. SVG drawings can be interactive and be changed dynamically with, you guessed it, computer code.  A green circle, for example, can be turned yellow by a piece code known as a function or command.  We’ll learn all about them.  Our first task is to bring in a bitmap graphic of a traffic light and combine that with our SVG.  A bitmap graphic is a jpeg or a png file.  A regular image.  You can find hundreds of traffic lights on the web. Here is what we are looking for:  traffic light png – Google Search  Try to find one that is open licensed.  Save that to your local drive.

After you have found your image, do the following:

  1. Click on the SVG button on the HTML Editor.  That brings us to the SVG editor.
  2. Select the image tool (see screenshot) and click anywhere on the canvas to place the image.
  3. Select the traffic lights that you downloaded.

 

Combine Vector Graphics with the Bitmap

After we imported our traffic light bitmap, we’ll draw circles to cover up the lamps.

  1. Select the ellipse (circle) tool and draw a perfect circle by holding down the shift key and dragging.    Color the circle gray by using the palette at the bottom of the screen.
  •  Clone or rubberstamp the selected circle to cover up the yellow and red lamps.

 

 

Make a note of the ID of each circle

SVG elements such as rectangles, circles, and paths have an automatically generated unique id.  It is like a serial number or a social security number.  We can use this id to target the svg element and change its properties.  Here is how to view the ID.  For now just take note of where it is.

  1. Select one of the circles. 
  2. Look for the id on the toolbar of the SVG editor.
  3. Note that each of the ids of the circles is similar with, perhaps, only one digit difference.

Create the push button to operate the lights

  1. Create two more circles as pictured below.  Use the fill tool (the bucket) to give the inner circle a gradient.
  2. Select both circles and use the G key to group them into one object.
  3. Click on the ‘Fit to Content’ button to size the canvas to the objects.  Be sure no object is left at the edge.  You may need to move your objects in a little so that they are not cut off.

Add a branch option

Now comes the interesting part.  We will add a branch option to the button we just created (the grouped circles).

  1. Right click on the button and select ‘Select Branch Options’.  These are the branch options that get executed when the object is first selected.  Optionally, the ‘De-select branch options’ get executed when the object is deselected (i.e. clicked on a second time).
  • From the Branch Options dialog, select Execute Commands.  Then select the ‘Edit’ button to enter the script editor.
  • In the script editor, click forcefully on the first line to activate the editor.

Enter your script (code)

What happens when a student or trainee clicks on the button is decided by what you type into the script editor.

In plain language, here is what we are attempting to do:

  • Get long term value of current light  (it is stored between clicks)
  • If current light is not a number, assign 0 to it
  • If current light is less than 3, add 1, else set it to 1
  • Save the value of current light into long term memory
  • Turn all lamps gray
  • Switch to a different path based on value of current light

In other words we want the traffic light to progress from green to yellow to red to green after every click.  To store the last light that was illuminated, we need to define a place in the computer’s memory.  Now let’s get to the code.

  1. Type in each of the following lines and then read an explanation of what it accomplishes.

var currentLight = getValue(“currentLight”);

Expanation:  “currentLight” is a slot in the computer’s memory.  We store the value of the lit traffic light there.  1 = green; 2 = yellow; 3 = red;

getValue is a function.  The purpose of this function is to retrieve the value that is stored in memory.

Functions often have an input and an output.  In this case, the string of characters “currentLight” serve as the input.  The output is the actual value stored in memory.

We assign the output of getValue to a local variable called currentLight.  currentLight is a local variable and “currentLight” (with quotes) is the label of the memory slot that holds a value for longer term storage.

Local variables disappear once the block of code has been executed; the longer term storage labeled “currentLight” persists for the life of the activity.

Variable names are case sensitive, must be one word, and can’t start with a number or symbol.

The keyword ‘var’ tells the computer that currentLight is intended to be a variable.  The = sign is actually an assignment operator.  That means that the output of getValue is assigned to the variable.

Technically, a copy of the value is made and stored in the local variable.

Lastly, the semi-colon at the end of the line terminates the line.  It’s a computer geeky way of punctuating the line so that the computer can make sense of it.

var isNum = isNumber(currentLight);

Explanation:  The isNumber function takes the input of currentLight (i.e. the value that currentLight holds) and returns true if the value is a number and false if it is not.  The first time this code is run, isNumber will return false because currentLight is “undefined”.  We haven’t stored anything yet.  True or false gets assigned to a local variable called ‘isNum’.  Once again, var identifies isNum as a variable.

if(!isNum){

      currentLight = 0;

}

Explanation:  We’ve now seen the use of a function and the use of a variable.  Here is our first conditional statement or, in other words, the ‘if’ statement.    Let’s first look at a simpler if statement and then we’ll return to the trickier one.  Type the following:

if(currentLight < 3){

    currentLight = currentLight + 1;

}

else{

    currentLight = 1;

}

Explanation: The keyword ‘if’ is followed by parentheses.  If the expression inside the parentheses evaluates to true, then the first block is executed.  The first block is defined by the curly braces.  {   }.  If the expression inside the parentheses evaluates to false, then the else block is executed.  The else block is defined by the second set of curly braces.  So, if currentLight holds the value of ‘1’, then 1 is indeed less than 3.  Therefore the expression inside the parentheses evaluates to true.  The code in the first block gets executed, which means that currentLight is assigned the old value currentLight plus 1.  In other words, currentLight is assigned the value of 2.

With those rules in mind, let’s return to the first conditional if statement.  The first time this code executes, currentLight will be undefined. Is ‘undefined’ a number?  No it is not.  Therefore isNum is assigned the value of false.  The expression inside the first if parentheses is !isNum.  The ! symbol makes this a bit tricky.  It inverts the value of isNum.  If isNum is false it now evaluates to ‘true’.  The if statement evaluates to true when currentLight is undefined.  The outcome is that currentLight is initialized with the value of 0.  So the very first time we click, currentLight will equal 0 after the first if statement.  Now let’s move on to the second if statement.  Is 0 less than 3?  Yes.  Yes is synonymous to ‘true’.  Therefore currentLight will be assigned the old value of currentLight plus 1.  The old value of currentLight was 0.  0 + 1 is now 1.  After the second if statement, currentLight holds the value of 1.  So, to repeat, the very first time we click, currentLight ends up with the value of 1. 

setValue(“currentLight”, currentLight);

Explanation: setValue is a function that does the opposite of getValue.  setValue stores the value of currentLight in a memory slot labelled “currentLight”.  The slot in memory does not need to match the name of the variable.  The label, however, used in getValue must match the label used in setValue;

changeColor(“ls1617676199534_2”, “#CCCCCC”);

changeColor(“ls1617676199534_3”, “#CCCCCC”);

changeColor(“ls1617676199534_4”, “#CCCCCC”);

Explanation:  changeColor is a function.  It takes two inputs and does something with them.  Another word for input is argument.  That’s a really geeky term.  Who’s arguing?  Nevertheless, inputs are called arguments.  The first argument or input is ID of the element whose color property we are changing.  By that I mean the circle.  You cannot use my values.  You need to follow an earlier step and use the IDs of your circles.  They will be different.  You can ‘Save and Close’ and return to this code after you copied the circle ID’s to a notepad. The second argument is the color value.  Now, here is another geeky thing.  It is common to express computer colors with hexadecimal values.  # means hexadecimal.  The first pair of CC is equivalent to the decimal value of 210.  The three pairs of CC create the color gray.  We could substitute “#CCCCCC” with the word “gray”.  It is a slightly different shade of gray.  I prefer #CCCCCC, but admit that “gray” is simpler.

Finally, type the following:

switch(currentLight){

    case 1:

changeColor(“ls1617676199534_2”, “#00FF00”); 

break;

    

    case 2:

        changeColor(“ls1617676199534_3”, “#FFFF00”);  

        break;

    case 3:

         changeColor(“ls1617676199534_4”, “#FF0000”); 

        break;

}

Explanation: The ‘switch’ statement is another type of conditional like the ‘if’ statement.  It’s like a train track switch.  Train #1 goes down the case 1: track.  Train #2 goes down the case 2: track, and so forth.  What is train 1?  That is what currentLight evaluates to.  If currentLight holds the value of 1, we go down the first track and execute changeColor(“ls1617676199534_2”, “#00FF00”), which means that we turn the first lamp green.  We could replace  “#00FF00” with “green”.  If currentLight holds the value of 2, then we change the second circle to yellow.  If currentLight holds 3, then we change the third circle to red.  Our code only permits 1, 2 or 3.  That is because our second if statement, resets currentLight to 1 when currentLight reaches 3.

The hexadecimal values represent three pairs.  The first pair is Red.  The second pair is Green.  The third pair is Blue.  FF0000 means full red and no green and no blue, which produces the red color.  #00FF00 means no red, full green, and no blue, which produces the green color.  FFFF00 means full red, and full green and no blue, which produces yellow.  In computer color, equal amounts of red and green light produce yellow light.

So here is the code in its entirety.  If you simply cut and paste, the code wouldn’t work because the SVG element IDs would be incorrect.

var currentLight = getValue(“currentLight”);

var isNum = isNumber(currentLight);

if(isNum){

   currentLight = currentLight;

}

      else{

            currentLight = 0;

}

if(currentLight < 3){

    currentLight++;

}else{

    currentLight = 1;

}

setValue(“currentLight”, currentLight)

changeColor(“”, “#CCCCCC”);

changeColor(“”, “#CCCCCC”);

changeColor(“”, “#CCCCCC”);

switch(currentLight){

    case 1:

        changeColor(“”, “#00FF00”); 

        break;

    case 2:

        changeColor(“”, “#FFFF00”);  

        break;

    case 3:

         changeColor(“”, “#FF0000”); 

        break;

}

Test your code

  1. Click on the ‘Test’ button.  The test won’t reveal logic errors but it will highlight basic issues like forgetting a semi-colon or misspelling the name of a function.   The real test comes when you preview the project in a browser.

Save and Preview

  1. Click on the ‘Save and Close’ button (to the right of ‘Test’) to save your script and exit the editor and return to the Branch Options dialog.
  2. Click on the ‘Save’ button to exit the Branch Options dialog.
  3. Click on the ‘Save to Page’ to save and exit the SVG Editor.
  4. Click “Preview in Browser” to see your project work.  Go to page two and click on the button to change the traffic light.  If this worked for you, leave a comment. If not, edit your traffic lights. Back in the LodeStar, click on the traffic light on the page, then when the image dialog opens, select ‘Edit’.

 

Conclusion

You did it.  You learned how to use a variable to store a value.  You learned the definition of a function and how to use one.  (You can find more LodeStar functions by clicking on the ‘Help’ button in the script editor. )  You also learned two types of conditional statements:  the “if” and the “switch”.  With the use of variables, functions, and conditional statements, the sky is the limit in terms of what you can do.  We’ll soon publish a more thorough article on LodeStar functions and what they can do.  In the meantime, the next best step is to create your own simple project.  Don’t rush into applying this to a ‘real’ project.  Play a little first.  Soon you will be able to achieve a higher degree of interactivity, store learner information, create branching conditions based on the information, and much much more.