> ## Documentation Index
> Fetch the complete documentation index at: https://docs.activecalculator.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Embed SDK

> Use our Embed SDK to interact with calculators on your website.

<Check>Embed SDK is available only to [paid plans](https://activecalculator.com/pricing).</Check>

## Overview

Our Embed SDK lets you interact with calculators embedded on your web pages. It provides methods to listen for changes, access elements, and update values, giving you full control over your embedded calculators.

<Warning>
  If you embedded your calculator before August 26, 2024, you may need to update the embed code on your website. The new embed code now includes the Embed SDK automatically. Previously, only the iframe code was provided.
</Warning>

<Note>
  To use the Embed SDK, toggle the **"Enable JS API"** option in your calculator settings.
</Note>

## Methods

### Initialize Embed SDK

The SDK automatically initializes when the calculator is embedded on your page. You don't need to call an explicit init function.

### Get Calculator Instance

Retrieves an instance of the calculator for interaction.

```javascript theme={null}
const calculatorInstance = activeCalculator.getInstance("YOUR_CALCULATOR_ID");
```

<ParamField path="calculatorId" type="string" required>
  {" "}

  The unique identifier for your calculator instance{" "}
</ParamField>

This method returns a calculator instance that you can use to interact with your embedded calculator.

### Wait for Calculator Ready State

```javascript theme={null}
window.addEventListener("activeCalculatorReady", function () {
  const calculatorInstance = activeCalculator.getInstance("YOUR_CALCULATOR_ID");
  // Your code here
});
```

### Get Element Instance

Retrieves a specific element from the calculator for interaction.

```javascript theme={null}
const element = calculatorInstance.getElementInstance("ELEMENT_REF");
```

<ParamField path="elementRef" type="string" required>
  {" "}

  The reference identifier for the specific element within the calculator{" "}
</ParamField>

This method returns an element instance that you can use to interact with a specific part of your calculator.

### Listen for Calculator Events

Sets up a listener for calculator-wide events.

```javascript theme={null}
calculatorInstance.on("interaction", function (response) {
  const { elementReference, value, calculationData, responseData } = response;
  console.log("Interaction detected:", elementReference, value);
});
```

<ParamField path="event" type="string" required>
  {" "}

  The name of the event to listen for (e.g., "interaction"). Only the "interaction"
  event is supported at the moment.{" "}
</ParamField>

| Event       | Description                                            |
| ----------- | ------------------------------------------------------ |
| interaction | Triggered when a visitor interacts with the calculator |

<ParamField path="handler" type="function" required>
  {" "}

  The callback function to execute when the event occurs{" "}
</ParamField>

This method allows you to react to any interaction within the calculator.

### Listen for Element Events

Sets up a listener for events on a specific element.

```javascript theme={null}
const element = calculatorInstance.getElementInstance("ELEMENT_REF");

element.on("valueChange", function (data) {
  console.log("New value:", data.value);
  console.log("Calculation data:", data.calculationData);
  console.log("Response data:", data.responseData);
});
```

<ParamField path="event" type="string" required>
  {" "}

  The name of the event to listen for (e.g., "valueChange"). Only the "valueChange"
  event is supported at the moment.{" "}
</ParamField>

| Event       | Description                                     |
| ----------- | ----------------------------------------------- |
| valueChange | Triggered when the value of the element changes |

<ParamField path="handler" type="function" required>
  {" "}

  The callback function to execute when the event occurs{" "}
</ParamField>

This method allows you to react to changes in a specific element of the calculator.

### Set Answer

Sets the value for a specific element in the calculator.

```javascript theme={null}
calculatorInstance.setAnswer("ELEMENT_REF", newValue);
```

<ParamField path="elementRef" type="string" required>
  {" "}

  The reference identifier for the element to update{" "}
</ParamField>

<ParamField path="newValue" type="union" required>
  The new value to set for the element. The type depends on the element:

  * For number and range slider inputs: `number`
  * For text inputs (email, phone, website, short text, long text): `string`
  * For file upload: `string[]`
  * For select and radio button: `{ id: string; value: number; label: string; }`
  * For checkboxes: `{ id: string; value: number; label: string; }[]`
</ParamField>

This method allows you to programmatically update the value of a specific element in the calculator.

#### Examples

<CodeGroup>
  ```javascript Number Input theme={null}
  calculatorInstance.setAnswer("NUMBER_INPUT_REF", 42);
  ```

  ```javascript Range Slider theme={null}
  calculatorInstance.setAnswer("RANGE_SLIDER_REF", 75.5);
  ```

  ```javascript Text Input theme={null}
  calculatorInstance.setAnswer("EMAIL_INPUT_REF", "user@example.com");
  ```

  ```javascript File Upload theme={null}
  calculatorInstance.setAnswer("FILE_UPLOAD_REF", ["file1.jpg", "file2.pdf"]);
  ```

  ```javascript Select or Radio Button theme={null}
  // First, get the interactive elements
  const interactiveElements = calculatorInstance.getInteractiveElements();

  // Find the select element by its ref
  const selectElement = interactiveElements.find(element => element.ref === "SELECT_ELEMENT_REF");

  // Get the first option from the select element
  const selectOption = selectElement.settings.options[0];

  calculatorInstance.setAnswer(selectElement.ref, selectOption);
  ```

  ```javascript Checkboxes theme={null}
  // First, get the interactive elements
  const interactiveElements = calculatorInstance.getInteractiveElements();

  // Find the checkboxes element by its ref
  const checkboxesElement = interactiveElements.find(element => element.ref === "CHECKBOXES_ELEMENT_REF");

  // Get the first two options from the checkboxes element
  const checkboxOptions = checkboxesElement.settings.options.slice(0, 2);

  calculatorInstance.setAnswer(checkboxesElement.ref, checkboxOptions);
  ```
</CodeGroup>

### Get Answer

Retrieves the current value of a specific element in the calculator.

```javascript theme={null}
const currentValue = calculatorInstance.getAnswer("ELEMENT_REF");
```

<ParamField path="elementRef" type="string" required>
  {" "}

  The reference identifier for the element to retrieve the value from{" "}
</ParamField>

This method returns the current value of a specific element in the calculator.

## Additional Methods

### Get Answer from Element

Retrieve the current value of a specific element in the calculator.

```javascript theme={null}
const currentValue = element.getAnswer();
```

### Set Answer for Element

Set a new value for a specific element in the calculator.

```javascript theme={null}
element.setAnswer(newValue);
```

<ParamField path="newValue" type="union" required>
  The new value to set for the element. The type depends on the element:

  * For number and range slider inputs: `number`
  * For text inputs (email, phone, website, short text, long text): `string`
  * For file upload: `string[]`
  * For select and radio button: `{ id: string; value: number; label: string; }`
  * For checkboxes: `{ id: string; value: number; label: string; }[]`
</ParamField>

#### Examples

<CodeGroup>
  ```javascript Number Input theme={null}
  const numberInputInstance = calculatorInstance.getElementInstance("NUMBER_INPUT_REF");
  numberInputInstance.setAnswer(42);
  ```

  ```javascript Range Slider theme={null}
  const sliderInstance = calculatorInstance.getElementInstance("RANGE_SLIDER_REF");
  sliderInstance.setAnswer(75.5);
  ```

  ```javascript Text Input theme={null}
  const emailInputInstance = calculatorInstance.getElementInstance("EMAIL_INPUT_REF");
  emailInputInstance.setAnswer("user@example.com");
  ```

  ```javascript File Upload theme={null}
  const fileUploadInstance = calculatorInstance.getElementInstance("FILE_UPLOAD_REF");
  fileUploadInstance.setAnswer(["file1.jpg", "file2.pdf"]);
  ```

  ```javascript Select or Radio Button theme={null}
  const selectInstance = calculatorInstance.getElementInstance("SELECT_REF");

  // Get the interactive elements to access the options
  const interactiveElements = calculatorInstance.getInteractiveElements();
  const selectElement = interactiveElements.find(el => el.ref === "SELECT_REF");

  // Get the first option from the select element
  const selectOption = selectElement.settings.options[0];

  selectInstance.setAnswer(selectOption);
  ```

  ```javascript Checkboxes theme={null}
  const checkboxesInstance = calculatorInstance.getElementInstance("CHECKBOXES_REF");

  // Get the interactive elements to access the options
  const interactiveElements = calculatorInstance.getInteractiveElements();
  const checkboxesElement = interactiveElements.find(el => el.ref === "CHECKBOXES_REF");

  // Get the first two options from the checkboxes element
  const checkboxOptions = checkboxesElement.settings.options.slice(0, 2);

  checkboxesInstance.setAnswer(checkboxOptions);
  ```
</CodeGroup>

### Get Interactive Elements

Retrieve all interactive elements from the calculator.

```javascript theme={null}
const interactiveElements = calculatorInstance.getInteractiveElements();
```

This method returns an array of all elements in the calculator that can be interacted with, such as input fields, dropdowns, and sliders.

#### Response

<ResponseField name="interactiveElements" type="array">
  An array of objects, each representing an interactive element in the calculator.

  <Expandable title="properties">
    <ResponseField name="ref" type="string">
      The unique reference identifier for the element.
    </ResponseField>

    <ResponseField name="type" type="string">
      The type of the interactive element (e.g., "rangeSlider", "number").
    </ResponseField>

    <ResponseField name="title" type="string">
      The display title of the element.
    </ResponseField>

    <ResponseField name="variable" type="string">
      The variable name associated with the element.
    </ResponseField>

    <ResponseField name="settings" type="object">
      An object containing the specific settings for the element.
    </ResponseField>
  </Expandable>
</ResponseField>

#### Example

<CodeGroup>
  ```json Sample Response theme={null}
  [
      {
          "ref": "ArOP8",
          "type": "rangeSlider",
          "title": "Range Slider",
          "settings": {
              "max": 100,
              "step": 1.5,
              "prefix": "$",
              "variant": "default",
              "defaultValue": 0,
              "decimalPlaces": 2,
              "alwaysShowValue": true,
              "displayValueEditable": true
          },
          "variable": "rangeSlider"
      },
      {
          "ref": "LLAR-",
          "type": "number",
          "title": "Number",
          "settings": {
              "defaultValue": 0,
              "useMouseControls": true
          },
          "variable": "number"
      }
  ]
  ```

  ```javascript Usage Example theme={null}
  const calculatorInstance = activeCalculator.getInstance("YOUR_CALCULATOR_ID");
  const interactiveElements = calculatorInstance.getInteractiveElements();

  // Get element references
  const rangeSliderRef = interactiveElements.find(element => element.type === "rangeSlider").ref;
  const numberInputRef = interactiveElements.find(element => element.type === "number").ref;

  // Use element references to get element instances
  const rangeSlider = calculatorInstance.getElementInstance(rangeSliderRef);
  const numberInput = calculatorInstance.getElementInstance(numberInputRef);

  // Now you can interact with these elements
  rangeSlider.on("valueChange", function(data) {
    console.log("Range slider value changed:", data.value);
  });

  numberInput.setAnswer(50);
  ```
</CodeGroup>

### Get Custom Variables

Retrieve all custom variables defined in the calculator.

```javascript theme={null}
const customVariables = calculatorInstance.getCustomVariables();
```

This method returns an array of custom variables that have been defined in the calculator configuration.

#### Response

<ResponseField name="customVariables" type="array">
  An array of objects, each representing a custom variable in the calculator.

  <Expandable title="properties">
    <ResponseField name="id" type="string">
      The unique identifier for the variable.
    </ResponseField>

    <ResponseField name="title" type="string">
      The display title of the variable.
    </ResponseField>

    <ResponseField name="variable" type="string">
      The name of the variable used in calculations.
    </ResponseField>

    <ResponseField name="expression" type="string">
      The mathematical expression used to calculate the variable's value.
    </ResponseField>
  </Expandable>
</ResponseField>

#### Example

<CodeGroup>
  ```json Sample Response theme={null}
  [
      {
          "id": "EX1Ap",
          "title": "Loan",
          "variable": "loan",
          "expression": "100 * @number"
      }
  ]
  ```

  ```javascript Usage Example theme={null}
  const calculatorInstance = activeCalculator.getInstance("YOUR_CALCULATOR_ID");
  const customVariables = calculatorInstance.getCustomVariables();

  console.log(customVariables[0].title);       // Output: "Loan"
  console.log(customVariables[0].expression);  // Output: "100 * @number"
  ```
</CodeGroup>

### Get Calculation Data

Retrieve the current calculation data from the calculator.

```javascript theme={null}
const calculationData = calculatorInstance.getCalculationData();
```

This method returns an object containing all the current values and calculated results in the calculator.

#### Response

<ResponseField name="calculationData" type="object">
  An object containing the current state of the calculator's fields and variables.

  <Expandable title="properties">
    <ResponseField name="fields" type="object">
      A record of all interactive elements in the calculator.

      <Expandable title="value types">
        <ResponseField name="number" type="number">
          A numeric value for number inputs.
        </ResponseField>

        <ResponseField name="string" type="string">
          A string value for text inputs.
        </ResponseField>

        <ResponseField name="string[]" type="array of strings">
          An array of strings for multi-select inputs.
        </ResponseField>

        <ResponseField name="number[]" type="array of numbers">
          An array of numbers for numeric multi-select inputs.
        </ResponseField>

        <ResponseField name="option" type="object">
          An object representing a single selected option.

          <Expandable title="Option Properties">
            <ResponseField name="id" type="string">
              The unique identifier of the option.
            </ResponseField>

            <ResponseField name="value" type="number">
              The numeric value associated with the option.
            </ResponseField>

            <ResponseField name="label" type="string">
              The display label for the option.
            </ResponseField>
          </Expandable>
        </ResponseField>

        <ResponseField name="option[]" type="array of objects">
          An array of option objects for multi-select inputs.
        </ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="variables" type="object">
      A record of all calculated variables in the calculator.

      <ResponseField name="[variableName]" type="number">
        The calculated value for each variable.
      </ResponseField>
    </ResponseField>
  </Expandable>
</ResponseField>

#### Example

<CodeGroup>
  ```json Sample Response theme={null}
  {
      "fields": {
          "rangeSlider": 0,
          "number": 0
      },
      "variables": {
          "loan": 0
      }
  }
  ```

  ```javascript Usage Example theme={null}
  const calculatorInstance = activeCalculator.getInstance("YOUR_CALCULATOR_ID");
  const calculationData = calculatorInstance.getCalculationData();

  console.log(calculationData.fields.rangeSlider);  // Output: 0
  console.log(calculationData.variables.loan);      // Output: 0
  ```
</CodeGroup>

This example shows a sample response from `getCalculationData()` and how to access the values in your code.

### Get Response

Retrieve the current response data from the calculator.

```javascript theme={null}
const responseData = calculatorInstance.getResponse();
```

This method returns an object containing the current response data, which may include formatted results or additional information based on the calculator's configuration.

#### Response

<ResponseField name="responseData" type="object">
  An object containing key-value pairs where keys are element references or variable names, and values can be of various types:

  <Expandable title="value types">
    <ResponseField name="boolean" type="boolean">
      A true/false value.
    </ResponseField>

    <ResponseField name="string" type="string">
      A text value.
    </ResponseField>

    <ResponseField name="number" type="number">
      A numeric value.
    </ResponseField>

    <ResponseField name="option" type="object">
      An object representing a selected option.

      <Expandable title="Option Properties">
        <ResponseField name="id" type="string">
          The unique identifier of the option.
        </ResponseField>

        <ResponseField name="value" type="number">
          The numeric value associated with the option.
        </ResponseField>

        <ResponseField name="label" type="string">
          The display label for the option.
        </ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="option[]" type="array">
      An array of option objects for multi-select inputs.
    </ResponseField>

    <ResponseField name="any" type="any">
      Any other type of value not covered by the above.
    </ResponseField>
  </Expandable>
</ResponseField>

## Debug Mode

To enable debug mode in ActiveCalculator, add `?activeCalculatorDebug=true` to your app's URL.

For example, if you've embedded your ActiveCalculator instance in your app hosted at [https://example.com](https://example.com), you can activate debug mode by changing the URL to:

```
https://example.com?activeCalculatorDebug=true
```

After adding this parameter, refresh the page and open your browser's developer console (usually by pressing F12 or right-clicking and selecting "Inspect" then navigating to the "Console" tab).

## Example: Mortgage calculator

In this example, we're showing how to make life easier for users by automatically filling in the interest rate when they pick a mortgage term. We've got default rates ready to go, but you can totally swap these out with fresh rates from your backend whenever you need to keep things up-to-date.

<Frame caption="Mortgage calculator with custom backend rates">
  <video autoPlay muted loop playsInline className="w-full aspect-video" src="https://mintcdn.com/activecalculator/tPVPFWdsTY5CMzAQ/videos/embed-sdk-morgage-example.mp4?fit=max&auto=format&n=tPVPFWdsTY5CMzAQ&q=85&s=4502a5718d78e7fdd2f33bba87db9e47" data-path="videos/embed-sdk-morgage-example.mp4" />
</Frame>

First, let's set up our default interest rates based on mortgage terms:

```javascript global-config.js theme={null}
// You can fetch the latest rates from your backend here
// Store default weekly interest rates based on mortgage terms
window.mortgageDefaults = {
  5: 2.75, // 5 years
  10: 3.25, // 10 years
  15: 3.75, // 15 years
  30: 4.25, // 30 years
};
```

Now, let's implement the ActiveCalculator integration:

```javascript mortgage-calculator.js theme={null}
// Wait for the ActiveCalculator to be ready
window.addEventListener("activeCalculatorReady", function () {
  // Get the calculator instance
  const calculatorInstance = activeCalculator.getInstance(
    "MORTGAGE_CALCULATOR_ID"
  );

  // Get specific element instances
  const mortgageTermSelect = calculatorInstance.getElementInstance(
    "MORTGAGE_TERM_SELECT_REF"
  );

  // Listen for value changes on the mortgage term select
  mortgageTermSelect.on("valueChange", function (data) {
    console.log("Mortgage term changed:", data.value);

    // Update the interest rate based on the selected mortgage term
    const defaultRate = window.mortgageDefaults[data.value.value] || 3.5; // Default to 3.5 if not found
    calculatorInstance.setAnswer("INTEREST_RATE_FIELD_REF", defaultRate);
  });
});
```

This example demonstrates a more realistic scenario for a mortgage calculator:

1. We define global default interest rates based on mortgage terms in `global-config.js`.
2. In `mortgage-calculator.js`, we set up the ActiveCalculator integration:
   * We get instance of the mortgage term select field.
   * We listen for changes on the mortgage term select and update the interest rate accordingly.
