The following are code snippets that can be used in the project file that you download below. The snippet will correlate to the slide number within Storyline. Download the project file first and then follow along with Jeff as he walks you through how to apply the code.
Storyline Variables: variableTest
This code is to get our feet wet with how JavaScript works with getting and setting code.
let variableTest = getVar("variableTest");
alert(variableTest)
let variableTest = getVar("variableTest");
let updatedVariable = variableTest + 15;
setVar("variableTest", updatedVariable);
Storyline Variables: month, todaysDate
The following code will grab the date and then we can use that to change the background image.
let currentTime = new Date();
let month = currentTime.getMonth() + 1;
let day = currentTime.getDate();
let year = currentTime.getFullYear();
let dateString = month + "/" + day + "/" + year;
setVar("month", month);
setVar("todaysDate", dateString);
Storyline Variables: currentTime, hours
This next code will detect the time of day and then change the image if it is day time or night time.
let currentDate = new Date();
let hours = currentDate.getHours();
let minutes = currentDate.getMinutes();
let timeStamp = hours + ":" + minutes;
setVar("currentTime", timeStamp);
setVar("hours", hours);
Storyline Variables: timer
This will create a time independent of the slide timeline and then show layers depending on the seconds of the timer.
var sec = 0;
function startTimer(){
sec += 1;
setVar("timer",sec);
if (sec == 100) {
clearInterval(timerId);
}
}
timerId=setInterval(startTimer,1000);
Storyline Variables: countDown
Instead of counting up, this will now start a countdown and change the text based on it hitting 0.
var sec = 10;
function startTimer(){
sec -= 1;
setVar("countDown",sec);
if (sec < 0) {
clearInterval(timerId);
setVar("countDown","Times Up")
}
}
timerId=setInterval(startTimer,1000);
Storyline Variables: deviceType
You can use this code to detect the device and then change the image based on the device.
setVar("deviceType", getOS())
function getOS() {
var userAgent = window.navigator.userAgent,
platform = window.navigator?.userAgentData?.platform || window.navigator.platform,
macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'],
windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'],
iosPlatforms = ['iPhone', 'iPad', 'iPod'],
os = null;
if (macosPlatforms.indexOf(platform) !== -1) {
os = 'Mac OS';
} else if (iosPlatforms.indexOf(platform) !== -1) {
os = 'iOS';
} else if (windowsPlatforms.indexOf(platform) !== -1) {
os = 'Windows';
} else if (/Android/.test(userAgent)) {
os = 'Android';
} else if (/Linux/.test(platform)) {
os = 'Linux';
}
return os;
}
Storyline Variables: queryName, queryAge
Query strings allows us to pass in different information into the course and then update variables based on the URL used.
let urlValues = window.location.search;
let searchParams = new URLSearchParams(urlValues);
let name = searchParams.get('name');
let age = searchParams.get('age');
setVar("queryName", name)
setVar("queryAge", age)
// ?name=Jeff&age=20
Storyline Variables: entryNum1, entryNum2, calc1, calc2
Now lets get more complex by animating these cards one at a time and adding a hover state.
let num1 = getVar("entryNum1");
let num2 = getVar("entryNum2");
let percentage = Math.round((num1 / num2) * 100);
let complexMath = (num1*500) + (num2*800) / 6;
setVar("calc1", percentage);
setVar("calc2", complexMath);
Storyline Variables: n/a
On this page we will add 3 different code snippets that animate various objects to our stage. Inspect and look for "slide-layer base-layer".
let square = document.querySelector("[data-model-id='67Brye1BGUS']");
gsap.to(square, { yPercent: 200, rotation: 180 })
let triangle = document.querySelector("[data-model-id='6nmK88deM2z']");
gsap.to(triangle, { rotation: 360, repeat: 3, yoyo: true })
let circle = document.querySelector("[data-model-id='6WeMR6qfIen']");
gsap.to(circle, { yPercent: 200, duration: 2, ease: "bounce.out", onComplete: runFunc});
function runFunc(){
alert("Finished!");
}
//gsap.to(circle, { scale: 2});
Storyline Variables: n/a
Now lets get more complex by animating these cards one at a time and adding a hover state.
// Selecting the elements
let features = document.querySelectorAll("[data-model-id='5vcGqLIG41f'], [data-model-id='6iZojGZhmC7'], [data-model-id='5vAXbgfhW2P']");
// Scale up
features.forEach(function(feature) {
feature.addEventListener('mouseover', function() {
gsap.to(feature, {scale: 1.06, ease: "back.out"});
});
});
// Scale down
features.forEach(function(feature) {
feature.addEventListener('mouseout', function() {
gsap.to(feature, {scale: 1, ease: "back.out"});
});
});
Storyline Variables: n/a
Now lets get more complex by animating these cards one at a time and adding a hover state.
let info_3 = document.querySelector("[data-model-id='5vXZIC8hemU']");
let saturn = document.querySelector("[data-model-id='6UUPXBcnH4s']");
let bar1 = document.querySelector("[data-model-id='6Wuqf7fIGsI']");
let bar2 = document.querySelector("[data-model-id='6U8Ep4sLFeW']");
let bar3 = document.querySelector("[data-model-id='6HSEVEPpCs0']");
let bar4 = document.querySelector("[data-model-id='6HXtAAnPFYs']");
let bar5 = document.querySelector("[data-model-id='5XuxXfSldHw']");
gsap.fromTo(info_3, { scale: 0, rotation: -90 }, {scale: 1, rotation: 0, delay: 0.5, ease: "back.out"});
gsap.to(saturn, {rotation: 80, yoyo: true, duration: 3, repeat: -1, ease: "power.inOut"});
gsap.to(bar1, {yPercent: 70, yoyo: true, duration: 3, repeat: -1})
gsap.to(bar2, {yPercent: -55, yoyo: true, duration: 4, repeat: -1})
gsap.to(bar3, {yPercent: 50, yoyo: true, duration: 6, repeat: -1})
gsap.to(bar4, {yPercent: -60, yoyo: true, duration: 3.5, repeat: -1})
gsap.to(bar5, {yPercent: 80, yoyo: true, duration: 8, repeat: -1})
Storyline Variables: fruit1, fruit2, fruit3, fruit4, fruit5, randomFruit
This code needs variables to choose form in Storyline and then an end result and it will randomly pick one of those variables. You can then update the path based on that variable.
// Get the variables
let fruit1 = getVar("fruit1");
let fruit2 = getVar("fruit2");
let fruit3 = getVar("fruit3");
let fruit4 = getVar("fruit4");
let fruit5 = getVar("fruit5");
// Place the variables into an array
let fruitArray = [fruit1, fruit2, fruit3, fruit4, fruit5];
// Function to randomly select one item from the array
function getRandomItem(array) {
let randomIndex = Math.floor(Math.random() * array.length);
return array[randomIndex];
}
// Get a random item from the array
let randomFruit = getRandomItem(fruitArray);
// Output the random item
setVar("randomFruit", randomFruit);
Storyline Variables: learnersName, score, completionDate
This code needs variables to choose form in Storyline then it will push information back into the certificate and have the information from Storyline in the certificate. Just place the certificate in the same published file.
// Get the values of the variables
var name = encodeURIComponent(getVar("learnersName"));
var score = encodeURIComponent(getVar("score"));
var date = encodeURIComponent(getVar("completionDate"));
// Construct the URL with query parameters
var certURL = "certificate.html?name=" + name + "&score=" + score + "&date=" + date;
// Open the certificate page in a new tab
window.open(certURL, "_blank");
You can download the zipped certificate.html file here. Or generate your own from ChatGPT.
Storyline Variables: note1, note2, note3
This code will collect notes from Storyline variables and open them in a printable HTML page. The notes are passed as query parameters to a separate HTML file.
var notes = [
{ title: "Page 1 Notes", body: getVar("note1") },
{ title: "Page 2 Notes", body: getVar("note2") },
{ title: "Page 3 Notes", body: getVar("note3") }
];
// Build query string with repeated parameters: t= for title, n= for note body
var params = new URLSearchParams();
notes.forEach(function (item) {
params.append("t", item.title || "");
params.append("n", item.body || "");
});
// Open the printable notes HTML in a new tab
var url = "pagenotes.html?" + params.toString();
window.open(url, "_blank");
You can download the zipped pagenotes.html file here. Or generate your own from ChatGPT.
Storyline Variables: n/a
Use this code to change the mouse icon when you hover over an object. To follow along you will need to create an object and get the model ID.
let targetObject = document.querySelector("[data-model-id='']");
if (targetObject) {
targetObject.addEventListener('mouseover', function () {
targetObject.style.cursor = 'url("../upside-down-cursor.png"), auto';
});
targetObject.addEventListener('mouseout', function () {
targetObject.style.cursor = 'default';
});
}
Storyline Variables: score
This code shows you how you can save information in local storage and then pull the data from local storage.
// Get the value of the Storyline variable
var score = getVar("score");
// Store the variable in local storage
localStorage.setItem("score", score);
// Get the value from local storage
var storedScore = localStorage.getItem("score");
// If the value exists, update the Storyline variable
if(storedScore !== null) {
setVar("score", parseInt(storedScore));
}
setVar("score", 0);
localStorage.removeItem("score");
//localStorage.clear();.
alert(localStorage.getItem("score"));
Storyline Variables: n/a
The following code will help you bring master slide objects to the front and have them always show on top. You will have to find the model id for the group.
let controls = document.querySelector("[data-model-id='6OHbxekDD4N']");
controls.style.zIndex = "9999"
Storyline Variables: learnerName, learnerID, courseStatus, score
Now lets get more complex by animating these cards one at a time and adding a hover state.
let userName = lmsAPI.GetStudentName();
let array = userName.split(',');
let updatedName = array[1] + ' ' + array[0];
setVar("learnerName", updatedName);
let studentID = lmsAPI.GetStudentID();
setVar("learnerID", studentID);
let status = decodeStatus(lmsAPI.GetStatus());
setVar("courseStatus", status);
function decodeStatus(intStatus){
var stringStatus = "";
switch(intStatus){
case 1:
stringStatus = "Passed";
break;
case 2:
stringStatus = "Incomplete";
break;
case 3:
stringStatus = "Failed";
break;
case 4:
stringStatus = "Unknown / Not Set";
break;
default:
break;
}
return stringStatus;
}
lmsAPI.SetPassed();
lmsAPI.SetFailed();
lmsAPI.ResetStatus();
let score = getVar("score");
lmsAPI.SetScore(score, 100, 0);
if (score >= 70) {
lmsAPI.SetPassed();
} else{
lmsAPI.SetFailed();
}
alert("Score has been set");