js Functions: Expressions vs Statements

Feb 06, 2015

I'm not great with JavaScript, and I think I've been staring at the screen for too long.  This is probably a scope issue, but I don't really understand why, or what I need to do to fix it.

I have a function.  I need to call the function when the timeline starts, and again later when a button is pressed.  I can't figure out how to make this work.  

I've placed the function (written as a statement) on the 'timeline starts' trigger, and everything is fine.

function myFunction(message) {
alert("message")
}

But when I click my button the function doesn't invoke.  But it will invoke if I re-write the function as an expression:

myFunction = function(message) {
alert("message")
}

Only that breaks the 'start timeline' invocation!  Grrr.  

I tried using window.myFunction, but that didn't seem to help.  (Or maybe it did help, but I've been staring at this too long and missed it.)

The only solution I can come up with is to have two almost identical functions, one a statement and the other an expression, which seems inelegant since one of the purposes of functions is re-use.

Can anyone explain what is going on (in small words) and propose a solution?

4 Replies
Sharon Huston

@Phil, Thanks!  I guess I'll use separate files.  I normally try to avoid this solution because I always forget to either modify the HTML or add the file to the Story package, but choices seem limited.  For the record, I can successfully invoke a function from another trigger, but the function has to be written as an expression, which is weird to me.  

@Jackson, thank you, but this is a just a stripped-down example.  Each function contains a bunch of code, and yes, it needs to run as a function because I was hoping to call it repeatedly from different places in the Storyline file.

Norm Cousineau

I would expect that window.myFunction = function(){...};

then

window.myFunction();

should work. Note that each time the timeline starts, you'll be redefining the function, which is no big deal but unnecessary. You could try :

if (!window.myFunction) window.myFunction = function(){...};

Also, my preference is to namespace any global variables. What if Storyline has a global function named the same as yours...you'll overwrite it. Could do something like : window.mydomain = {}; window.mydomain.myFunction = function(){...};

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