Counting with JavaScript

Jun 17, 2017

I'm wondering how to recreate the counting function that is native within Storyline in Javascript.

For example:

In Storyline, you can create a variable and then use the +Add operator to count the number of times a user clicks a button:

Action: Adjust variable
Variable: noOfClicks
Operator: + Add
Value: Value   1
When: User Clicks
Object: Button

In Javascript, you could do something like the following but there is something missing. With the code below, it will set the "jsClicks" variable to 1 but subsequent clicks do not increment the count up.

var player = GetPlayer( );
var noOfClicks = 0;
noOfClicks ++;
player.SetVar("jsClicks",noOfClicks);

What would I need to do to increment it up each time the user clicks the Button object?  

Thanks for the help.

 

6 Replies
OWEN HOLT

That being said... try something like this.

I used a SL numeric variable I called "ClickCount" with a default value of "0". The following code worked to increase the count incrementally by one each time the user clicked the button that the code was attached to.

var player=GetPlayer();
var clicks = player.GetVar("ClickCount") +1;
player.SetVar("ClickCount",clicks);

Richard Watson

Owen,

That accomplishes what I was playing around with. Thank you.

In regard to your earlier question, "If it can be done in the player, why not use the player..." 

I realize I can do this in the player but I have multiple other things going on in an interaction that I'm playing with and I wanted to see how much of it I could incorporate into the actual javascript itself.  Call it an experiment if you will; just learning what I can and cannot do with it at the moment.

Thanks again for the sample.

Richard

 

 

 

Math Notermans

Basically this is a scope issue. When you define a variable in a specific scope. In this case your page or interaction wherever the action is happening... then setting it to 0 as you do here... and the adding 1 (++) you resetting the variable to 0 each time.
To solve this with javascript and scope in mind.. you would need to add an initialization of the variable somewhere at start of the course... so when you add
var noOfClicks; ( or var noOfClicks = 0; )
at the start of your course...it is initialized...empty, but initialized..
From then on you can add anything in that variable...
If at some page you count the no of Clicks... like this
noOfClicks ++;
It will count properly.

This discussion is closed. You can start a new discussion or contact Articulate Support.