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)
ScreenIndex (index = 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)
HackShowState (state = null)
HackServerResponse (responseData = 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, callback)
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()
ResetInputs()
UnlockButtons()
Query(keym, value = null)

LogInfo(title, desc)
OverrideValidation(pass = true, message = null)

$.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');
    }
}

$.ScreenIndex

Purpose Programmatically change screen or get the index of current screen.

Arguments 1 optional

  • int: Screen number

Returns Index of screen if argument is not provided.

Sample

btn.addEventListener('click', function() {
    $.ScreenIndex(2)
})

$.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 2nd 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 or 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])
    }
}

$.HackInputs(null, [0, 1, "Test", [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)
    }
}

$.HackShowState

Purpose Returns or set form state. Very advanced thing.

Arguments 1, optional "form"|"wait"|"done"

Returns If no argument is provided, then it returns current form state.

Sample

if (screen == 1) {
    if (input == 0) {
        $.HackShowState("wait")
        setTimeout(function() {
            $.HackShowState("form")
        }, 1000)
    }
}

$.HackServerResponse

Purpose Returns or set server response. Can be used to emulate server response for non-submitting forms/apps in combination with $.HackShowState. Very advanced thing.

Arguments 1, optional

object: {
    t: title,
    p: photo,
    lo: layout
}

Returns If no argument is provided, then it returns current form state.

Sample

if (screen == 1) {
    if (input == 0) {
        $.HackServerResponse({
            t: title,
            p: photo,
            lo: layout
        })
        $.HackShowState("wait")
        setTimeout(function() {
            $.HackShowState("done")
        }, 1000)
    }
}

$.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
  • function: callback

Sample

$.Fetch('https://.../json', {}, async function(res) {
    let x = await res.json();
    console.log(x);
})

$.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 : boolean
REQ_BADGE : boolean
KEYBOARD : boolean
PROGRESS : boolean
NEXT_BUTTON_TEXT: string (Default: "Next")
BACK_BUTTON_TEXT: string (Default: "Back")
SUBMIT_BUTTON_TEXT: string (Default: "Submit")
ERROR_CLASSES: string (Default: "bg-danger text-white")

Arguments 2, both required

  • string: element
  • boolean|string: true to show, false to hide, string for value if requires.

In case of ERROR_CLASSES, Bootstrap classes can be used or classes from imported css or own theme's css.

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()

$.ResetInputs

Purpose Resets all inputs to initial state. Can be used by copying inputs in a variable and then call this to reset inputs and then on specific screens, copy inputs back by using $.HackInputs

Arguments none

Returns none

Sample

let inps = $.HackInputs();

$.ResetInputs()
for (let i = 0; i <= 2; i++) {
    $.HackInputs(i, inps[i]);
}

$.UnlockButtons

Purpose Unlocks actions buttons.

Arguments none

Returns none

Sample

$.UnlockButtons()

$.LogInfo

Purpose Add entry in logs side bar

Arguments 2, required

  • string: title
  • string: description

Returns none

Sample

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

$.OverrideValidation

Purpose Override validation behavior with a behavior. Useful in implementing custom validations using plugins or own logic.

Arguments 2, required

  • boolean: Override validation
  • string: Error Message

Returns none

Sample

$.Handle(`screen_0_on_next_pre`, function() {
    if (inputs[0] == 'test') {
        $.OverrideValidation (false, "You cannot use this name.");
    }
})

$.Query

Purpose Sets of Gets value of query string in current url.

Arguments key: string value: string, optionals

Returns query string value if value argument is not provided.

Sample

let q = $.Query('item');