Javascript adding problems
Oct 30, 2015
Hey all,
I'm new to Storyline 2 (coming from Captivate) and am running into issues with multiple variable addition. In the past (e.g. captivate) I could set a function of x = w+y+z... where each time it gets called it an update to the status of x.
Doing this in Storyline 2 is arduous, especially when copy/pasting triggers (5 of them) to over 50 object :) So, I've resorted to Javascript but am running into issues. Instead of the variables being added (1+1+1+1=4) I am getting a string (1+1+1+1=1111, or 1+2+1+3=1213). Here is my JS script:
var player = GetPlayer();
var prog1 = player.GetVar("train");
var prog2 = player.GetVar("shake");
var prog3 = player.GetVar("fun");
var prog4 = player.GetVar("world");
var progTotal = prog1+prog2+prog3+prog4;
player.SetVar("total",progTotal);
What am I missing?
6 Replies
Are your Storyline variables (e.g. train, shake, etc.) NUMERICAL variables? I used your script and it works for me.
I've attached my project file. What ends up happening is that it tracks (10, 101, 1011, etc) until each parameter equals 1. Then it works and totals 4.
If a variable = 0 , does Javacscript run into an issue pulling in that number?
my next step will be to change it to True/False statements and writing "if" code to set the JS var to 1 and add from there
Hi, Bryce -- As I see you are new to the E-Learning Heroes Community, I first wanted to say, "Welcome!" And unfortunately, I am not equipped to provide support for JS coding, but I'm glad to see that Michael is helping you out, and I am sure others will chime in, as well. Just in case you need it, here is a link to our JS Best Practices information. Best of luck! :)
Bryce,
I think JavaScript is treating your JavaScript variables as strings so it is concatenating the values rather than add them. Perhaps this line will do the trick:
var progTotal = Number(prog1)+Number(prog2)+Number(prog3)+Number(prog4);
That did it! Thank you so much.
I ended up externalizing this to a separate JS file, adding some console.log commands and watching what happened. As a great learning lesson I cannot express enough how beneficial it is to use an external JS script! It made troubleshooting, and editing code a breeze.
The JS console is dreamy:) I've also used Chrome's "Sources" tab in Developer Tools to make local edits to the user.js file when testing on a server. Between this and console execution, troubleshooting / updates go much more quickly.
This discussion is closed. You can start a new discussion or contact Articulate Support.