Skip to content

JavaScript Api

Aliveforms provides a useful JavaScript API.

Usable elements

In Aliveforms, JavaScript API has access to following elements

Element Information
input input of current screen
inputs array of all inputs of visitor
weights array of weights of screens
screen number/index of screen
uploads files uploaded by user
$ Aliveforms API Object

Boot

In Aliveforms, __boot() can be used to execute JavaScript code before first screen. It can be used to setup variables and modify theme etc.

Aliveforms API Object

The Aliveforms JavaScript API Object provides following functions.

JavaScript API
Util.Equals (a, b)
Alert (message)
Emit(title, detail);
Handle(event, function);
ChangeFlow (screen)
ChangePrevious (screen, value)
ChangeNext (screen, value)
PreviousScreen(value = null)
Run_Logic_On_Back(mode)
Multiply (screen, factor)
Add (screen, factor)
Var (varName, value = null)
ScreenCounter(value = null)
ScreenTitle (index, newTitle = null)
ScreenOptions(index, newOptions)
ScreenPhoto (index, newPhoto = null)
OptionTitle (sc_index, op_index, newTitle = null)
OptionPhoto (sc_index, op_index, newPhoto = null)
GetTimer()
SetStyle (variable, value)
HackForm (index = null, newData = null)
HackInputs (index = null, newData = null)
HackWeights (index = null, newData = null)
GetAnswers (index = null)
GetOptionsCount(index)
IsCorrect (index)
GetCorrectOptionTitle (index)
IsAnswerable (index)
SetGroup (group, value)
GetGroup (group = null)
ListGroup ()
GetDominantGroup ()
CalculatePercentage (group = null)
Fetch (url, options)
Storage.session.set (id, value)
Storage.session.get (id)
Storage.session.remove (id)
ImportScript(scriptUrl, callback)
ImportStyle (scriptUrl, callback = null)
DisplayElement(param, value = null)
PressNext()
PressBack()
ParseString(string)
RegisterErrorHandler()
LogInfo(title, desc)

$.Util.Equals

Purpose Compare if two values or arrays are equal

Arguments 2, both required - primitive types or array

Returns bool

Sample

if (screen == 1) {
    if ($.Util.Equals(inputs[0], input)) {
        $.Alert('Both answers are same')
    }
}

$.Alert

Purpose Shows a toast

Arguments 1, String

Returns none

Sample

if (screen == 1) {
    if ($.Util.Equals(inputs[0], input)) {
        $.Alert('Both answers are same')
    }
}

$.Emit

Purpose Emit event to be listened on webpage where form is embedded via iframe.

Arguments 2, both required

  • string: title of event
  • Object: detail of event Returns none

Sample

$.Emit('close');
on webpage:
const el = document.getElementById('fabCheckbox');
const iframe = document.getElementById('wapp');
window.addEventListener('message', function (event) {
    console.log('message', event, event.detail);
    if (event.source === iframe.contentWindow && event.data === 'close') {
        el.click();
    }
});

$.Handle

Purpose Registers event handler for events dispatched in Aliveforms.

Arguments 2, both required

  • string: title of event
  • callback: function to handle event

Returns none

Sample

$.Handle('screen_0_on_enter', function() {
    $.LogInfo('on_enter', 'Enter');
});

$.ChangeFlow

Purpose Changes the flow on question. Determines what question to show next.

Arguments 1, int

Returns none

Sample

// suppose options are 0: yes 1: no
if (screen == 1) {
    if (input == 1) {
        $.Alert('Changing flow');
        $.ChangeFlow(3);
    }
}

$.ChangePrevious

Purpose Changes the previous question to show when back is pressed.

Arguments 2, both required ints

  • int: screen index
  • int: screen number

Returns none

Sample

// suppose options are 0: yes 1: no
if (screen == 1) {
    if (input == 1) {
        $.ChangePrevious(3, 1);
    }
}

$.ChangeNext

Purpose Changes the next question to show when back is pressed. It is different from ChangeFlow as it alters permanent value of default next screen.

Arguments 2, both required ints

  • int: screen index
  • int: screen number

Returns none

Sample

// suppose options are 0: yes 1: no
if (screen == 1) {
    if (input == 1) {
        $.ChangeNext(3, 1);
    }
}

$.PreviousScreen

Purpose Sets or Returns the index of previous screen. If no argument is provided, returns the index of previous screen. If argument is provided, it sets the value of previous screen. Useful in implementing conditional branching and checking from which screen use came from.

Arguments 1, optional - value

Returns Previous Screen Index

Sample

let prev = $.GetPreviousScreen();
if (prev == 1) {
    $.Alert('Jumped from Screen 1');
} else if (prev == 2) {
    $.Alert('Jumped from Screen 2');
}

$.Run_Logic_On_Back

Purpose By default, Aliveforms logic run only when next button is clicked. When this function is called with true, logics also execute on back button click. Can be run on any screen however, must be run on -1 or __boot()

Arguments 1, boolean

Returns none

Sample

if (screen == -1) {
    $.Run_Logic_On_Back(true);
}

$.Multiply

Works only with Analytical Forms

Purpose Multiples the weight of screen with a number.

Arguments 2, both required

  • integer: screen number
  • number: factor

Returns result

Sample

if (screen == 2) {
    if (input == 1) {
        $.Multiply(1, screen * 10);
    }
}

$.Add

Works only with Analytical Forms

Purpose Adds to the weight of screen with a number.

Arguments 2, both required

  • integer: screen number
  • number: factor

Returns result

Sample

if (screen == 2) {
    if (input == 1) {
        $.Add(1, screen * 10);
    }
}

$.Var

Purpose Returns the value of variable if 2nd argument is not provided else defines a variable with can be used in title and messages with [[VAR.NAME]].

Arguments 2, 1 required - 1 optional

  • string: Variable Name
  • any: Variable value (optional)

Returns Values of variable if 2nd argument is not provided.

Sample

if (screen == 1) {
    if (input == 1) {
        $.Var('factor', 1.5);
    }
}

$.ScreenCounter

Purpose Sets the value of counter - the number shown before title of screen. It is useful if form data is set using loop.

Arguments 1, optional

  • int: counter number

Returns Value of counter no argument is passed

Sample

$.ScreenCounter(1)

$.ScreenTitle

Purpose Returns the screen title if 2nd argument is not provided else sets title of screen number.

Arguments 2, 1 required - 1 optional

  • int: Screen number
  • string: Screen title (optional)

Returns Title of screen if 2nd argument is not provided.

Sample

if (screen == 1) {
    if (input == 0) {
        $.ScreenTitle(2, 'Welcome with Yes');
    } else {
        $.ScreenTitle(2, 'Welcome with No');
    }
}

$.ScreenOptions

Purpose Returns the options of mcq screen if 2nd argument is not provided else sets options of provided screen index.

Arguments 2, 1 required - 1 optional

  • int: Screen number
  • array of objects: Screen options (optional)

option object can have following properties

t: title p: url of photo

Returns options of screen if 2nd argument is not provided.

Sample

let options = [{t: "Hello"}, {t: "World"}]
$.ScreenOptions(2, options)

$.ScreenPhoto

Purpose Returns the screen photo url if 2nd argument is not provided else sets the photo of screen number.

Arguments 2, 1 required - 1 optional

  • int: Screen number
  • string: url of photo (optional)

Returns Url of photo if 2nd argument is not provided.

Sample

if (screen == 1) {
    if (input == 0) {
        $.ScreenPhoto(2, 'https://example_image/yes.png');
    } else {
        $.ScreenPhoto(2, 'https://example_image/no.png');
    }
}

$.OptionTitle

Purpose Returns the title of option of screen if 3rd argument is not provided else sets the title of options of screen number.

Arguments 3, 2 required - 1 optional

  • int: Screen number
  • int: Option Number
  • string: title (optional)

Returns title of option of screen if 3rd argument is not provided.

Sample

if (screen == 1) {
    if (input == 0) {
        $.OptionTitle(2, 0, 'Yes Again');
    }
}

$.OptionPhoto

Purpose Returns the url photo of option of screen if 3rd argument is not provided else sets the photo of options of screen number.

Arguments 3, 2 required - 1 optional

  • int: Screen number
  • int: Option Number
  • string: url of photo (optional)

Returns url of option of screen if 3rd argument is not provided.

Sample

if (screen == 1) {
    if (input == 0) {
        $.OptionPhoto(2, 0, 'https://example_image/no.png');
    }
}

$.GetTimer

Purpose Returns reference to timer (interval). Useful to handle intervals. Check example.

Arguments none.

Sample

clearInterval($.GetTimer())

$.SetStyle

Purpose Set CSS variable values

Arguments 2, both required

string: variable string: value

Returns none

List of variables

body-background-color

body-background-image

body-background-repeat

body-background-size

body-background-style

body-color

border-active-color

border-color

border-radius

font-normal

font-title

option-active-bg

option-active-fg

option-bg

option-fg

primary-bg

primary-fg

secondary-bg

secondary-fg

stage-background

stage-blur

Sample

__boot() {
    $.SetStyle("stage-blur", "4px");
    $.SetStyle("primary-bg", "#fff");
}

$.HackForm

Purpose Returns the javascript object screen or sets the value of javascript object. if second argument is null, it returns the value, otherwise it sets the value.

Arguments 2, bot optional

  • int: Screen number
  • object: Option Number

Returns javascript object of screen of screen if 2nd argument is not provided. javascript object of form of screen if first argument is also not provided.

Sample

if (screen == 0) {
    if (input == 0) {
        const frm = $.HackForm(1);
        frm.t = "Hello";
        $.HackForm(1, frm);
    }
}

$.HackInputs

Purpose Returns the user inputs if 2rd argument is not provided else sets the inputs of screen number if first argument is provided, else changes all inputs.

Arguments 2, optional

  • int: Screen number
  • any: input

Returns input of screen if 2nd argument is not provided. complete inputs array of screen if first argument is also not provided.

Sample

if (screen == 1) {
    if (input == 0) {
        $.HackInputs(0, 1)
    }
}

if (screen == 2) {
    if (input == 1) {
        $.HackInputs(1, [0,1])
    }
}

$.HackWeights

Purpose Returns the weights/scores if 2rd argument is not provided else sets the weights/scores of screen number if first argument is provided, else changes all weights/scores.

Arguments 2, optional

  • int: Screen number
  • any: input

Returns weight/score of screen if 2nd argument is not provided. complete weight/scores array of screen if first argument is also not provided.

Sample

if (screen == 1) {
    if (input == 0) {
        $.HackWeights(0, 10)
    }
}

if (screen == 2) {
    if (input == 1) {
        $.HackWeights(1, 20)
    }
}

$.GetAnswers

Works only with score based forms having option 'load solution' enabled

Purpose Returns keys of correct answers. It is array of indices of correct options or text

Arguments none

Returns none

Sample

var answers;

__boot() {
    answers = $.GetAnswers();
}

// on result 

$.Define('MSG', JSON.stringify(answers));

// use this in message

Answers: [[VAR.MSG]]

$.OptionsCount

Purpose Get number of options in screen with give index. Then can be used with OptionTitle

Arguments int : screen index Returns int : number of options

Sample

var optCount = $.GetOptionsCount(1);

let title = [];
for (let i = 0; i < optCount; i++) {
    title = [...title, $.OptionTitle(0, i)];
}

console.log('titles:', title.join(','))

$.IsCorrect

Works only with score based forms having option 'load solution' enabled

Purpose

Check if answer of screen is correct. Arguments 1, required

  • int: index of screen

Returns bool

Sample

if (screen == 1) {
    if ($.IsCorrect(screen)) {
        $.Alert('WOW');
    }
}

$.GetCorrectOptionTitle

Works only with score based forms having option 'load solution' enabled

Purpose Returns title of correct options

Arguments 1, required

  • int: index of screen

Returns string of correct option title.

Sample

if (screen == 1) {
    if ($.IsCorrect(screen)) {
        $.Alert('WOW');
    } else {
        $.Alert($.GetCorrectOptionTitle(screen))
    }
}

$.IsAnswerable

Works only with score based forms

Purpose Checks if screen is answerable or not, i.e. it is list or option or text with answerable enabled.

Arguments 1, required

  • int: index of screen

Returns bool

Sample

if (screen == 1) {
    if ($.IsAnswerable(screen)) {
        // Do Something
    }
}

$.SetGroup

Purpose Sets values of group.

Arguments 2, both required

  • string: Group name
  • numeric: value

Returns none

Sample

if (screen == 1) {
    if (input == 0) {
      $.SetGroup('A', $.GetGroup('A') + 10);
    }
}

$.GetGroup

Purpose Returns the value of group Arguments 1, required

  • string: name of group

Returns value of group.

Sample

if (screen == 1) {
    if (input == 0) {
      $.SetGroup('A', $.GetGroup('A') + 10);
    }
}

$.ListGroup

Purpose Returns array of names of assigned groups.

Arguments None

Returns Array of strings

Sample

var groups = $.ListGroups();

$.GetDominantGroup

Purpose Returns the group with highest value,

Arguments none

Returns string

Sample

const group = $.GetDominantGroup();
$.Alert(`Your group is ${group}`);

$.CalculatePercentage

Purpose Returns percentage of groups.

Arguments 1, optional

  • string: name of group

Returns Array if group is not provided. Number if group is provided.

Sample

const groupA= $.CalculatePercentage('A');
const groupB= $.CalculatePercentage('B');
$.Alert(`Your group A is ${groupA}% and B is ${groupB}%`);

$.Fetch

Purpose A wrapper around JavaScript fetch api. Arguments 2, required

  • string: url
  • object: options

Returns bool

Sample

if (screen == 1) {
    if ($.Util.Equals(inputs[0], input)) {
        $.Alert('Both answers are same')
    }
}

$.Storage.session.get

Purpose Get value of variable stored in session storage.

Arguments 1, required

  • string: key

Returns any - value of key

Sample

var time = $.Storage.session.get('time');
if (!time) {
    time = $.Storage.session.set('time', 'Good Time');
}

if (screen == 1) {
    $.Alert(`Time is ${time}`);
}

$.Storage.session.set

Purpose Sets value of variable in session storage.

Arguments 2, both required

  • string: key
  • any: value

Returns none

Sample

var time = $.Storage.session.get('time');
if (!time) {
    time = $.Storage.session.set('time', 'Good Time');
}

if (screen == 1) {
    $.Alert(`Time is ${time}`);
}

$.Storage.session.remove

Purpose Removes value stored in session storage.

Arguments 1, required

  • string: key

Returns none

Sample

var time = $.Storage.session.get('time');
if (!time) {
    time = $.Storage.session.set('time', 'Good Time');
}

if (screen == 1) {
    $.Alert(`Time is ${time}`);
    $.Storage.session.remove('time');
}

$.ImportScript

Purpose Import JavaScript

Arguments 2, both required

  • string: url
  • callback: function to run when script loads Returns none

Sample

$.ImportScript('https://cdn.jsdelivr.net/npm/tsparticles-preset-firefly@2/tsparticles.preset.firefly.bundle.min.js', function() {
    if (typeof tsParticles !== "undefined") {
      (async () => {
        await tsParticles.load("tsparticles", {
          preset: 'firefly',
        });
      })();
    } else {
      console.error("tsParticles library is not available.");
    }
  });

$.ImportStyle

Purpose Import CSS stylesheet.

Arguments 2, both

  • string: url
  • callback: function to run when stylesheet loads

Returns none

Sample

$.ImportStyle('https://aliveforms.com/style.css', function() {
   $.Alert('loaded')
  });

$.DisplayElement

Purpose Show or hide element of form

INDEX
REQ_BADGE
KEYBOARD 
PROGRESS 

Arguments 2, both required

  • string: element
  • boolean: true to show, false to hide

Returns none

Sample

$.DisplayElement('INDEX', false)

$.PressNext

Purpose Emulate Next button pressing in logic.

Arguments none Returns none

Sample

$.PressNext()

$.PressBack

Purpose Emulate Back button pressing in logic.

Arguments none Returns none

Sample

$.PressBack()

$.ParseString

Purpose Parses the provided string as aliveforms strings and returns parsed string.

Arguments 1, required

  • string: element

Returns string

Sample

$.SetTitle (1, $.ParseString("Hi [[SCREEN.0]]"))

$.RegisterErrorHandler

Purpose Registers uncaught error handler.

Arguments none

Returns none

Sample

$.RegisterErrorHandler()

$.LogInfo

Purpose Add entry in logs side bar

Arguments 2, required

  • string: title
  • string: description

Returns none

Sample

$.LogInfo ("Info", "This is information")