Functions

Example 1: Create a function

To create a function (or in programming terms ‘Define’ a function) is straight forward, as long as you remember the correct syntax, such as remembering to use the word function provide a function name and parameters (optional) and insert both curly brackets { } one at the beginning and end of the function, you should have no problem. Functions are very useful because they can be ‘called’ by any object on a page (see Example 2 for more information) as many times as required. For example:

function CurrentScore(imageName, UserName)
{
 imageName.Show()
 var userScore = UserName + " your current score is "
  + SCORE_TOTAL
 feedback.SetSelection(0,-1)
 feedback.ReplaceSelection(userScore)
}

In this example, the function is named CurrentScore and its function is to tell the user their current score. Imagine your publication has a quiz page with several multiple choice questions on it. Each time the user presses an answer button, a Script Action on the button is triggered and it calls this function (see Example 2 below for more about calling functions). By placing the function in a Script Object, each button can call this function.

Example 2: Calling a function

To call a function (i.e. to run the list of instructions in a function) is really simple, all you need to do is to type the name of the function either in a Script Object or in a Script Action. To call the function in Example 1, use the following syntax:

CurrentScore(ImageCorrect, "John")

Because the function CurrentScore was defined as taking two parameters, you need provide those two pieces of data when calling the function. In this example, the first parameter in the function was named imageName and it is expecting an Image object on the current page; so when we call the function we enter the name of the image we want to send to the function, in this example an Image object named ImageCorrect. The first line of the function uses this information to show the image on screen. The second parameter in the function is UserName and we send the name of the user; in our example this is a string containing the name John – we could have entered a variable in here that contained the name of the user if we wanted to. The string is then used in the second line of the function.

Using the two examples above, we have briefly demonstrated how you can create a function and call a function. By passing parameters to a function you can make it carry out its list of instructions using different data each time. This is a very important part of programming; you want to make your code as generic as possible so that it can be used as often as possible.

Note:
If you never call a function, then the list of instructions in the function will never run.

Close