Days
Hours
Minutes
Seconds
x

Froala Editor v4.2.0 is Here LEARN MORE

Skip to content

Froala Charts API Methods

getObjectReference

static function

Returns the DOMElement created inside the chart container by Froala Charts. This is equivalent to accessing the DOMElement using the ref property.

Note: The returned DOMElement here is the <span> element created by Froala Charts to render the chart, and not the the container element specified as the value of the renderAt attribute.

Parameters

id

Type: string

ID of the chart, whose DOMElement is to be referenced.

Example

// Iterate on all charts rendered on a page and move them to a common location
var sidebar = document.getElementById('sidebar-html-div'), // assuming that your common container is this
chart;

for (chart in FroalaCharts.items) {
    sidebar.appendChild(FroalaCharts.getObjectReference(chart).parentNode);
}

// The above can be done without using this deprecated getObjectReference method.
for (chart in FroalaCharts.items) {
    chart = FroalaCharts.items[chart];
    chart.ref && sidebar.appendChild(chart.ref.parentNode);
}

clone

Creates a copy of a chart instance, creating a new chart with identical construction properties of the chart being cloned. The cloned chart, assigned an auto-generated ID, is rendered in a container DOM element that is explicitly provided.

Parameters

overrides

Type: object

Object containing instructions for changes in the cloned chart. For example, passing pieChart.clone({type: 'column'}); will clone the pie chart, but set its chart-type as column. It accepts all the construction parameters of a new Froala Chartsinstance.

argsOnly

Type: boolean

Set to true, if a new FroalaCharts object is not required. In that case, it causes the function to return a serializable object that can later be passed to create a new FroalaCharts instance, and therefore, create a clone.

Default value: false

chartType

Gets or sets the chart type of a FroalaCharts instance. To get the current chart type, call this function without any parameters. To set a new chart type, pass the chart type as the first parameter to this function. When a new chart type is set, the chart is automatically re-rendered and the chartTypeChanged event is triggered.

Parameters

value

Type: string

New chart type to set

options

dataSource

Type: string or object

New source of data while changing the chart type

dataFormat

Type: FroalaCharts~dataFormats

Data format for the new data source. If this is not provided, then the existing/default data format is used.

Note: If the dataSource parameter is not provided, the dataFormat parameter is ignored.

Example

// Render a column chart and on click of a button toggle it from column to pie and vice versa.
FroalaCharts.ready(function () {
    var chart = new FroalaCharts.{
        type: 'column',
        renderAt: 'chart-container',
        dataSource: 'weekly-sales.json',
        dataFormat: 'jsonurl'
    }).render();

    // Assign the functionality of toggling chart type when clicked on
    // a button (with an id toggle-chart-type).
    document.getElementById('toggle-chart-type').onclick = function () {
        if (chart.chartType() === 'column') {
            chart.chartType('pie');
        }
        else {
            chart.chartType('column');
        }
    };
});

addEventListener

static function

Listens to events across all FroalaCharts instances on a page and executes custom functions when an event is triggered.

Note: To listen to an event triggered by a specific chart, the non-static addEventListener method is used.

Parameters

type

Type: string or array

Type (name) of the event to listen to. To register the listener for multiple events in the same registration call, provide all event names as an array.

listener

Type: FroalaCharts~eventListener

Function to be exceuted when the event is triggered. If multiple listeners are bound to an event, the listeners are executed in the order of definition, with arguments specific to the triggered event.

Example

// Show a message when a number of charts have been rendered on a page.
FroalaCharts.ready(function {
    var counter = 0,
        threshold = 3;

    FroalaCharts.addEventListener("rendered", function (eventObject) {
        counter++;
        if (counter > threshold) {
            alert("More than " + threshold + "charts rendered!");
        }
    });
});

removeEventListener

static function

Removes the event listener(s) bound to an event.

Parameters

type

Type: string or array

Type (name) of the event whose listener(s) has to be removed

listener

Type: function

Listener function to remove

ready

static function

Allows to register callback functions that are executed when the FroalaCharts library is ready to be used. In general, the Froala Charts framework is ready after the DOMContentLoaded browser event has been triggered and all the initial dependent files/modules are available.

Multiple callbacks can be attached by calling this function any number of times. Callback functions are executed even when attached after the Froala Charts framework is ready.Therefore, it is recommended that all entry-point and initialization codes are written within the ready() function. This also helps to neatly organize all the code in a script file or the page <head> tag as well as contextually separate code from HTML blocks.

Parameters

readyCallback

Type: FroalaCharts~readyCallback

Callback function executed when the Froala Charts framework is ready

args

Type: *

Argument to be passed to the callback function

Default value: FroalaCharts

context

Type: function

To execute a function, passed using the fn parameter, in a different scope than the default Froala Chartsscope, pass the appropriate class object here.

Default value: FroalaCharts

Example

// Render a chart within a chart container `div` element.
	FroalaCharts.ready(function (FroalaCharts./span>) {
    var chart = new FroalaCharts.{
        type: "column",
        renderAt: "chart-container-div",
        dataSource: "my-chart-data.json",
        dataFormat: "jsonurl"
    });
    // Since we are in the `ready` block, the `chart-container-div`
    // element should be available by now.
    chart.render();
});

addEventListener

Used to listen to events triggered by a specific chart.

Note: To listen to events triggered by all charts on a page, the static addEventListener() method is used.

Parameters

type

Type: string or array

Type (name) of the event to listen to. To register the listener for multiple events in the same registration call, provide all event names as an array.

listener

Type: FroalaCharts~eventListener

Function to be exceuted when the event is triggered. If multiple listeners are bound to an event, the listeners are executed in the order of definition, with arguments specific to the triggered event.

removeEventListener

Removes the event listener(s) bound to an event using the addEventListener() method.

Parameters

type

Type: string or array

Type (name) of the event whose listener(s) has to be removed

listener

Type: function

Listener function to remove

setChartAttribute

Updates a chart's attributes with a new attribute-value pair, thus updating the chart's data definition root (the <chart> node in the XML data or the chart object in the JSON data).

This function is useful when a chart's configuration has to be updated after it has been rendered once. The function internally retrieves the last data set for the chart using the getJSONData() method ( or the getXMLData() method, for XML data). It then updates the chart object (or the <chart> element) using the new attribute-value pair and sets this data back to the chart.

Note: Setting the value of an attribute to null will cause the attribute to be removed from the definition and set to its default value.

Parameters

attributes

Type: object or string

To set/update multiple attributes at once, an object containing all the key-value pairs is passed. In case of a single value, a string that is the key (the attribute name) is passed.

value

Type: string

If the attributes parameter is a single string value, the value parameter contains the value for that key.

Example

// Here we would render a chart in a DOM element with an id, say "chart-container", and upon clicking the
// chart, we would toggle the visibility of its legend.
FroalaCharts.ready(function () {
    FroalaCharts.render({
        id: 'salesChart',
        type: 'pie',
        renderAt: 'chart-container',

        dataSource: {
            chart: {
                caption: 'Revenue distribution'
            },
            data: [
                { value: '22', label: 'Redistribution' },
                { value: '54', label: 'Internal Circulation' },
                { value: '24', label: 'Sale' },
            ]
        },

        events: {
            chartClick: function (event) {
                var chart = event.sender,
                    // Check whether legend is currently visible by fetching the showLegend attribute
                    legendVisible = !!+chart.getChartAttribute('showLegend');

                // Set the opposite of the current state of the legend's visibility.
                chart.setChartAttribute('showLegend', legendVisible ? '0' : '1');
            }
        }
    });
});

getChartAttribute

Fetches value of chart attributes explicitly applied to the root chart object (or the <chart> node element).

Note: To fetch a list of all attributes, do not pass any parameters to this function.

If any attribute requested is not set for the chart or is internally computed but not explicitly set, the value is returned as undefined. For example, for multi-series column charts, the default value of the showLegends attribute is 1. However, if the attribute is not included in the chart definition and its value is requested, the function returns undefined.

Parameters

attribute

Type: string or array

To fetch the value of a single attribute, pass the attribute name as a string. For multiple attributes, pass an array of attribute names. Values will be returned in the order of the attribute names in the array.

getXMLData

Fetches chart data in the XML format. This function needs to be called on an existing chart; if called on a chart that has no data set for it, it returns an empty <chart /> element.

Note: The getXMLData() function is shorthand for chart.getChartData('xml').

setXMLData

Sets chart data in the XML data format. When this function is called on a chart that has already rendered, it immediately updates the chart with the new data. The function can also be used to set data for a new chart.

Note: A preferrable alternative to using this method is to pass chart data to the dataSource attribute of the Froala Charts constructor.

Note: The setXMLData() function is shorthand for the setChartData() method, where the data format is set to xml. So, calling chart.setXMLData('<chart>...</chart') is the same as calling chart.setChartData('<chart>...</chart>', 'xml').

Parameters

data

Type: string or object

XML data to be set for the chart, as a string

setXMLUrl

Fetches chart data from the URL provided, in the XML format. When this function is called on a chart that has already rendered, it immediately updates the chart with the new data. The function can also be used to set data for a new chart.

Note: A preferrable alternative to using this method is to pass chart data to the dataSource attribute of the Froala Charts constructor.

Note: The setXMLUrl() function is shorthand for the setChartDataUrl() method, where the data format of the URL is set to xmlurl. So, calling chart.setXMLUrl('data.xml') is the same as calling chart.chart.setChartDataUrl('data.xml', 'xmlurl').

Parameters

url

Type: string

Path to the XML data file

setChartDataUrl

Fetches chart data from the URL provided and passes it to the setChartData() method.

If the chart is already rendered, it is updated with the new data as soon as it is fetched from the URL. If the chart is not rendered, data is fetched from the URL and stored locally till the chart is rendered.

Note: It is not recommended to use this method to set data for a new chart. A preferrable alternative is to pass the URL as value to the dataSource attribute in the FroalaCharts constructor.

Note: Froala Charts uses AJAX to transport data. Therefore, ensure that the chart is running from a web-server to prevent the browsers' restrictions of fetching local (file://) files.

Parameters

url

Type: string

URL to fetch the chart data

format

Type: FroalaCharts~dataFormats

Format of the data being fetched. If the value for this parameter is not a valid dataFormat, then the default or previously set data format is assumed.

Note: If the data format is already known, then the setJSONUrl() or the setXMLUrl() methods can be used.

Example

// Render a chart and fetch data from a JSON file and then when a button is pressed, change the data.
		FroalaCharts.ready(function () {
    var chart = new FroalaCharts.{
        type: "column",
        renderAt: "chart-container",
        dataSource: "weekly-sales.json",
        dataFormat: "jsonurl"
    }).render();

    // Assign the functionality of updating data to a button which already
    // exists in page body and has a specific Id.
    document.getElementById("data-update-button").onclick = function () {
        // Specify the new Url to fetch data from.
        chart.setChartDataUrl("average-employee-sales.json", "json");
    };
});

setChartData

Sets the data for a chart.

When this function is called on a chart that is already rendered, the chart is instantly updated with the new data. When it is used to set data for a chart before it has rendered, data is initially stored internally and is passed to the chart when it is rendered.

Note: A preferrable alternative to using the setChartData() method is to pass chart data to the dataSource attribute of the Froala Charts constructor.

Parameters

data

Type: string or object

Data to be passed to the chart

format

Type: FroalaCharts~dataFormats

Format of the data being passed. If the value for this parameter is not a valid dataFormat, then the default or previously set data format is assumed.

Note: If the data format is already known, then the setJSONData() or the setXMLData() methods can be used.

Example

// Create a chart in a page and pass data to it in `JSON` format and on click of a
// button update it with newer data.
FroalaCharts.ready(function () {
    var chart = new FroalaCharts.{
        type: "pie",
        renderAt: "chart-container",

                   dataSource: {
            chart: {
                caption: "Market Share",
                showPercentage: "1"
            },
            data: [
                { label: "Current Prototype", value: "30" },
                { label: "Revised Prototype", value: "35" },
                { label: "Previous Prototype", value: "25" },
                { label: "Recalled Prototype", value: "10" }
            ]
        },
        dataFormat: "json"
    }).render();

    // Set data on the chart using the setChartData function when a button is clicked.
    document.getElementById("update-data").onclick = function () {
        chart.setChartData({
            chart: {
                caption: "Market Share Impact",
                numberPrefix: "USD"
            },
            data: [
                { label: "Current Prototype", value: "13773" },
                { label: "Revised Prototype", value: "16069" },
                { label: "Previous Prototype", value: "11477" },
                { label: "Recalled Prototype", value: "4591" }
            ]
        }, "json");
    };
});

getChartData

Fetches the data set for a chart, in one of the valid dataFormats. The function needs to be called on an existing chart. If called on a chart that has no data, it returns an empty chart object for json data, an empty <chart /> node for xml data, and an empty string for csv.

Parameters

format

Type: FroalaCharts~dataFormats

Format in which chart data has to be retrieved

isRaw

Type: numeric or string

When set to 1 object names return in the same format as they were defined on the data source. Value can range from 0 to 1. Default value is 0.

Default value: 0

Example

// Render a chart and upon click of a button alert the chart's data in
// CSV format.
FroalaCharts.ready(function () {
    var chart = new FroalaCharts.{
        type: "column",
        renderAt: "chart-container",
        dataSource: "weekly-sales.json",
        dataFormat: "jsonurl"
    }).render();

    // Assign the functionality of retrieving and alerting CSV data to
    // click event of a button
    document.getElementById("alert-csv-data").onclick = function () {
        alert(chart.getChartData("csv"));
    };
});

dataReady

Determines whether a chart will render properly with the data set on it. This includes data that is set using the setChartData() or setChartDataUrl() methods.

If the function is unable to determine whether data is ready or not, it returns undefined.

The function returns true or false only after the chart has rendered (the renderComplete event is triggered). The function returns false when: no data is set faulty data is set data is incompatible with the chart type; for example, single-series data is set for a multi-series chart.

Parameters

available

Type: boolean

Setting this parameter to true returns the status of the data, irrespective of its compatibility with the chart type. In that case, this function will return false if data provided to the chart triggers the dataLoadError or dataInvalid events

Default value: false

transcodeData

static function

Froala Charts supports a number of formats in which data can be provided. Click here to view the list of formats supported. This function allows data to be transcoded from one supported format to another, without initializing a new instance of Froala Charts. It is very useful when you already have a set of data stored or prepared in one Froala Charts data format and want to convert it to another format. The fact that we do not need to instantiate a new FroalaCharts instance speeds the conversion process.

Parameters

data

Type: string or object

Data to transcode

source

Type: FroalaCharts~dataFormats

Source format

target

Type: FroalaCharts~dataFormats

Target format

advanced

Type: boolean

Request the transcoding to return data in a verbose format where it returns the conversion result along with additional trancosing information. In advanced mode, the returned data of this function is in the following format:

Property Type Description
data object, string Result of the transcoding process
error object Object containing the error message

Default value: false

Example

// We would convert JSON data that is already in FroalaCharts.data format into CSV data format.
FroalaCharts.ready(function () {
var salesData = {
        chart: {
            caption: "Harry's SuperMart",
            subCaption: "Top 5 stores in last month by revenue",
        },
        data:[{
            label: "Bakersfield Central",
            value: "880000"
        },
        {
            label: "Garden Groove harbour",
            value: "730000"
        },
        {
            label: "Los Angeles Topanga",
            value: "590000"
        },
        {
            label: "Compton-Rancho Dom",
            value: "520000"
        },
        {
            label: "Daly City Serramonte",
            value: "330000"
        }]
    };

    // Alert the data after converting it to CSV data format.
    alert(FroalaCharts.transcodeData(salesData, 'json', 'csv'));
});

feedData

Feeds real-time data to real-time charts and gauges.

Parameters

stream

Type: string

Real-time data for charts and gauges

getData

Returns the value of the data set for real-time charts and gauges.

getDataWithId

Returns a three-dimensional array that contains the data and the dataset IDs. Once the reference for the chart is obtained, this function can be invoked to retrieve data.

setData

Feeds real-time data to real-time charts and gauges.

Parameters

value

Type: number

Numeric value to feed to the real-time chart/gauge. For single-value gauges (LEDs, bulb, cylinder, and thermometer gauges), this is the only parameter required.

label

Type: string

For the angular gauge and the horizontal linear gauge, this parameter specifies the dial number.

stopUpdate

Stops a self-updating real-time chart/gauge from polling the server for real-time updates.

restartUpdate

Resumes real-time updates for a chart/gauge.

isUpdateActive

Returns true if real-time update is enabled for a chart. Returns false is real-time update is stopped using the stopUpdate() method.

clearChart

Clears the entire chart canvas when a real-time chart is being updated.

Note: An alternative to calling this function is using the Clear Chart option from the real-time context menu, on real-time charts. To activate the real-time context menu, set the showRTMenuItem (under the chart object) to 1.

setDataURL (Deprecated API)

Sets the URL to fetch the XML chart data from.

This method can be called only after the loaded event is triggered. Alternatively, the setXMLUrl() method can be used, which does not have this limitation.

getDataForId

Returns data for the given pointer (for real-time horizontal linear gauge) or dial (for real-time angular gauge) using its defined ID.

setDataForId

Sets data for a given pointer (for real-time horizontal linear gauge) or dial (for real-time angular gauge) using its defined ID.

hasRendered

Returns true if the chart has rendered successfully, false if it has not.

setTransparent (Deprecated)

Sets the background color of the container DOM element, within which the chart is rendered, as transparent.

Note: This is not to be confused with the chart's background.

Parameters

transparency

Type: boolean

Passing true implies that the chart is transparent.

isPlotItemSliced

Checks whether a particular slice of the pie/doughnut chart is sliced-out or sliced-in.

Parameters

index

Type: number

Index of the pie/doughnut slice being checked

Example

// Render a pie chart with some data in sliced out state, provide data index
// in an input textfield and get the sliced state of the pie on click of a button
FroalaCharts.ready(function () {
    var chart = new FroalaCharts.{
        type: "pie",
        renderAt: "chart-container",
        dataSource: "data.json",
        dataFormat: "jsonurl"
    }).render();

    // Get the sliced state of a pie returned when clicked on a button
    // (with an id pie-sliced-state). It picks the data index from
    // an input textfield (with id pie-data-index).
    document.getElementById("pie-sliced-state").onclick = function () {
        var dataIndex = document.getElementById("pie-data-index").value,
            slicedState = chart.isPlotItemSliced(dataIndex);
    };
});

slicePlotItem

Slices in/slices out a pie/doughnut slice.

Note: You have to provide a callback Function if asyncRender is set to 1 (default) where you get the svg-string as a parameter of the callback function. The boolean value determines if the plot item is sliced (true) or not (false). The callback implementation does not require the user to the renderComplete event.

Parameters

index

Type: number

Index of the pie/doughnut slice

slice

Type: boolean

If set to true, it will slice out a slice, which is in the sliced-in state. If the slice is already in the sliced-out state, the state is retained.

callBackFN( sliced)

Type: slicePlotItem-callBack

callBackFN is called only when slicePlotItem() completes its execution.

Example

// Render a pie chart, provide data index in an input textfield
// and toggle the sliced state of the pie on click of a button
FroalaCharts.ready(function () {
    var chart = new FroalaCharts.{
        type: "pie",
        renderAt: "chart-container",
        dataSource: "data.json",
        dataFormat: "jsonurl"
    }).render();

    // Toggle the sliced state of the pie when clicked on a button
    // (with an id pie-sliced-state). It picks the data index from
    // an input textfield (with id pie-data-index).
    document.getElementById("pie-sliced-state").onclick = function () {
        var dataIndex = document.getElementById("pie-data-index").value;
        chart.slicePlotItem(dataIndex);
    };
});

centerLabel

Configures the center label in a doughnut chart.

Parameters

labelText

Type: string

Text to be displayed as the center label in the doughnut chart

Optional parameter holding a host of configurable parameters, like the cosmetic properties, for the center label.

Note: The properties are case sensitive.

options

font

Type: string

Font face for the label text

fontSize

Type: string

Font size of the label text

bold

Type: boolean

Specifies whether bold formatting will be applied for the label text

italic

Type: boolean

Specifies whether the label text will be in italics

color

Type: hexcolor

Font color for the label text

alpha

Type: alpha

Font opacity for the label text

hoverColor

Type: hexcolor

Hover color for the label text

hoverAlpha

Type: alpha

Hover opacity for the label text

bgColor

Type: hexcolor

Background color for the label

bgAlpha

Type: alpha

Opacity of the label background

borderColor

Type: hexcolor

Border color for the label background

borderAlpha

Type: alpha

Opacity of the label background border

borderThickness

Type: number

Thickness of the label background border

borderRadius

Type: number

Radius for a rounded label background border

padding

Type: number

Padding between the extremities of the label and the inner periphery of the doughnut. For a rectangular label background, it is relative to any of the four corners. For a circular background, is the gap between the two concentric circles-the background border and the inner periphery.

textPadding

Type: number

For a rectangular label background, it is the gutter between the text and the background border. For a circular background, it is the minimum space between the background border and the containing circle of the text.

toolText

Type: string

Tooltip text for the label

Example

// Render a doughnut chart and set center label with some
	// configuring params on click of a button
FroalaCharts.ready(function () {
    var chart = new FroalaCharts.{
        type: "doughnut",
        renderAt: "chart-container",
        dataSource: "data.json",
        dataFormat: "jsonurl"
    }).render();

    // Assign the functionality of setting the center label when clicked on
    // a button (with an id set-center-label).
    document.getElementById("set-center-label").onclick = function () {
        chart.centerLabel("The central label", {bold: true, toolText: "center label tooltext"});
    };
});

startingAngle

Rotates the pie/doughnut chart to a specific angle or by a specific angle. The mode of operation is controlled by the optional second parameter.

Note: Starting angle of a pie/doughnut chart is the angle at which the starting face of the first data slice is aligned to. Each subsequent pie/doughnut slice is then drawn in the counter clock-wise direction.

Note: You have to provide a callback Function if asyncRender is set to 1 (default) where you get the angle provided as input as a parameter of the callback function.The callback implementation does not require to listen to the renderComplete event.

Parameters

angle

Type: degrees

Angle measure by which the pie/doughnut chart will be rotated

Default value: 0

relative

Type: boolean

Mode of operation for the rotation. Specifies whether the angle being set is relative to the current angle or is w.r.t absolute 0

Default value: false

callBackFN(angle)

Type: startingAngle-callBack

callBackFN is called only when startingAngle() completes its execution.

Example

// Render a pie chart and rotate the chart by 90 degrees on click of a button
	FroalaCharts.ready(function () {
    var chart = new FroalaCharts.{
        type: "pie",
        renderAt: "chart-container",
        dataSource: "data.json",
        dataFormat: "jsonurl"
    }).render();

    // Assign the functionality of rotating the chart by 90 degrees when clicked on
    // a button (with an id rotate-chart).
    document.getElementById("rotate-chart").onclick = function () {
        chart.startingAngle(90, true);
    };
});

zoomOut

Zooms out the zoom line chart by one level.

zoomTo

Zooms the zoom line chart to view a specific range of data.

Parameters

startIndex

Type: number

Index of the data point starting at which the chart will be zoomed into

endIndex

Type: number

Index of the data point until which the chart will be zoomed into

resetChart

Resets all the zooming, panning, and pinning actions performed on a zoom line chart.

setZoomMode

Switches between the zoom mode and pin mode of a zoom line chart programmatically.

Parameters

yes

Type: boolean

Set to true to activate the zoom mode, set to false to activate the pin mode

getViewStartIndex

Returns the index of the first visible data point (in order of its definition in the source data) on the canvas of a zoom line chart.

Note: You have to provide a callback function if asyncRender is set to 1 (default) where you get the starting index as a parameter of the callback function.The callback implementation does not require to listen to the renderComplete event.

Parameters

callBackFN(index)

Type: getViewStartIndex-callBack

callBackFN is called only when getViewStartIndex() completes its execution.

getViewEndIndex

Returns the index of the last visible data point (in order of its definition in the source data) on the canvas of a zoom line chart.

Note: You have to provide a callback function if asyncRender is set to 1 (default) where you get the starting index as a parameter of the callback function.The callback implementation does not require to listen to the renderComplete event.

Parameters

callBackFN(index)

Type: getViewEndIndex-callBack

callBackFN is called only when getViewEndIndex() completes its execution.

scrollTo

Scrolls the zoom-line chart to a particular position.

Parameters

scrollPosition

Type: Number

scrollTo is called to scroll the chart.

Range : 0 - 1

Default value: 0

print

Prints individual charts. It hides all elements on a page except the chart to print and then invokes the page printing function ( window.print()).

Note: This function works only for charts that have rendered completely, i.e. only after the renderComplete event has been triggered.

Parameters

options

hideButtons

Type: boolean

Hides all buttons on the chart

Default value: true

Example

// In this snippet of code, we will render a chart on a page and
// call the print method on the chart on click of a button.
FroalaCharts.ready(function () {
   FroalaCharts.render({
       type: 'column',
       dataFormat: 'jsonurl',
       dataSource: 'data.json',

       // assuming an HTML div element exists on the page
       renderAt: 'chart-container-div'

       events: {
           renderComplete: function (event) {
               // assuming a button exists on page with a specific id
               var button = document.getElementById('print-button');
               button.onclick = function () {
                   event.sender.print();
               };
           }
       }

   });
});

exportChart

Exports a chart as an image or as a PDF document.

To enable exporting of a chart, the exportEnabled attribute (of the chart object) should be set to 1.

When exporting is done programmatically using this method, the export configuration is passed as parameters to this function.

Note: The exportChart function remains undefined until the loaded event is triggered. The exporting process is initiated only after the renderComplete event is triggered.

To read on how you can export charts using the export-related context menu, click here.

Parameters

The exportChart method takes the following parameters:

options

exportFormat

Type: string

Export Format Description
png Exports the charts in the high quality lossless PNG format
jpg Exports the chart in the high quality JPEG image format
pdf Exports the chart as a PDF document

Default value: png

exportFileName

Type: string

File name for the chart being exported, excluding the extension. The extension is automatically appended depending on the value of exportFormat parameter.

Default value: FroalaCharts

exportTargetWindow

Type: string

When the exportAction parameter is set to download as , this parameter lets you configure whether the return image or PDF will open in the same window (as an attachment for download), or in a new browser window (_blank).

Default value: _self

exportHandler

Type: string

URL of the export server

exportAction

Type: string

Specifies whether the exported image will be sent back to the browser as download, or whether it will be saved on to the server.

Action Value Description
download The exported chart image or PDF will be downloaded as file.
save The exported chart will be saved on the server.

Note: For the charts to be saved on the server, you would need to setup your own export handling server.

Default value: download

exportCallback

Type: function

Callback JavaScript function executed when the export process is complete. If this parameter is not assigned a value, then the window.FC_Exported is executed.

Default value: FC_Exported

batchExport

static function

Exports multiple charts in a single image. This method either takes no arguments or takes an object as an argument.

Parameters

imageWidth

Type: number

Width of the exported image (of the charts)

Default value: Maximum chart width + 10

imageHeight

Type: number

Height of the exported image (of the charts)

Default value: (Total height of all charts + 5) * (number of charts + 1)

The configuration required for the chart(s) being exported can be provided in this object using the attributes given below:

id

Type: string

Valid FroalaCharts ID, to attach the chart on the main image

x

Type: number

x-coordinate for positioning the exported image

Default value: 5

y

Type: number

y-coordinate for positioning the exported image

Default value: previous chart's y-coordinate + 5

width

Type: number

Custom width for the exported image

Note: If only one value from the width and the height of the chart is provided, the value of the other is calculated in a way that the aspect ratio is maintained.

Default value: Current chart width

height

Type: number

Custom height for the exported image

Note: If only one value from the width and the height of the chart is provided, the value of the other is calculated in a way that the aspect ratio is maintained.

Default value: Current chart height

The configuration required for the exported image's background can be provided in this object using the attributes given below:

bgColor

Type: hexcolor

Background color for the exported image

Default value: #ffffff

bgImage

Type: string

Background image for the exported images

bgImageAlpha

Type: number

Transparency of the background image

bgImageX

Type: number

Starting x-coordinate for positioning the background image

bgImageY

Type: number

Starting y-coordinate for positioning the background image

bgImageWidth

Type: number

Width of the background image

Note: If only one value from the width and the height is provided, the value of the other is calculated in a way that the aspect ratio is maintained.

Default value: Original width of the image

bgImageHeight

Type: number

Height of the background image

Note: If only one value from the width and the height is provided, the value of the other is calculated in a way that the aspect ratio is maintained.

Default value: Original height of the image

exportTargetWindow

Type: string

Set to _self to open the exported image in the same window

Set to _blank to open the exported image in a new window

Default value: _self

exportAction

Type: string

Set to _save to save the exported image on the server

Set to _download to send back the image to the client as a download

Default value: _download

exportFileName

Type: string

Default file name (excluding the extension) for the exported image

exportHandler

Type: string

For server-side exporting: Path of the export handler (the ready-to-use scripts provided by Froala Charts)

For client-side exporting: DOM ID of the FroalaCharts Export Component embedded in the web page, along with the chart

Default value: _download

exportFormats

Type: string

List of formats in which the chart can be exported

The formats are separated using the | (pipe) character.

Default value: _download

exportCallback

Type: string

Name of the JavaScript function that is called when the export process finishes

exportAtClientSide

Type: string

Set to 1 to enable client-side exporting

Default value: _download

getSVGString

Fetches the SVG of a chart, created by FroalaCharts while rendering the chart, as a string.

Note: This function can be called only after the chart has rendered.

Note: You have to provide a callback Function if asyncRender is set to 1 (default) where you get the svg-string as a parameter of the callback function. The callback implementation does not require to listen to the renderComplete event.

Parameters

callBackFN( svgString )

Type: getSVGString-callBack

callBackFN is called only when getSVGString() completes its execution.

keepImages

Type: keepImages

To get the images present in the chart from the SVG string, set the parameter of keepImages object to 1.

lockResize

Controls a chart’s automatic resizing ability when its dimensions are in percentage. This function has to be called before a chart has rendered. Using the hasRendered() method can be useful here. If the lockResize() function is called without a parameter, it returns the current state of the resize lock.

Parameters

state

Type: boolean

Setting this parameter to true will lock the automatic percentage-based resizing. If resize is already locked, sending false unlocks it.

showChartMessage

Shows a text message on a chart.

Parameters

text

Type: string

Text message to be displayed

modal

Type: boolean

Boolean value to indicate whether the message will be shown on an overlay button or on the chart.

Default value: false

cancelable

Type: boolean

If set to true, the modal can be closed by clicking. Defaults to false.

Note: Applicable only if modal is set to true.

Default value: false

formatNumber

static function

Formats input numbers based on the formatting configuration passed. The function can be called globally on the Froala Chartsobject or on a specific instance of Froala Charts.

When called globally on the FroalaCharts object, the function applies the configuration settings to all numbers on the chart.

Parameters

num

Type: number

Number to be formatted

type

Type: string

When called globally on the FroalaCharts object, the function applies the configuration settings to all numbers on the chart. This parameter selectively formats numbers based on chart elements, by taking yaxisvalues, xaxisvalues, and datalabels as values.

Default value: datalabels

config

Type: object

Optional number formatting attributes to override the default number formatting options of a chart

Note: While calling formatNumber on the FroalaCharts object, this becomes the second parameter.

Example

console.log(FroalaCharts.formatNumber(1234.5)); // logs "1.2K"
	
console.log(FroalaCharts.formatNumber(1234.5, {
    numberPrefix: "$"
})); // logs "$1.2K"
// Calling number formatter on a chart instance when `renderComplete` event is fired.
FroalaCharts.ready(function () {
// Render a chart within a chart container `div` element.
    var chart = new FroalaCharts.{
        type: 'column',
        renderAt: 'chart-container-div',
        dataFormat: 'json',
        dataSource: {
            chart: {
                caption: "Quarterly sales summary",
                numberPrefix: "$",
                decimals: "2",
                forceDecimals: "1"
            }
            data: [
                { label: "Q1", value: "213345"},
                { label: "Q2", value: "192672"},
                { label: "Q3", value: "201238"},
                { label: "Q4", value: "209881"},
            ]
        },

        events: {
            renderComplete: function (eventObj) {
                // Call the formatNumber function of the specific chart we rendered.
                console.log(eventObj.sender.formatNumber(1234.5)); // logs "$1.23K"
            }
        }
    });
    chart.render();
});

getJSONData

Fetches chart data in the JSON format. This function needs to be called on an existing chart; if called on a chart that has no data set for it, it returns an empty chart object.

Note: This function is shorthand for chart.getChartData('json').

Parameters

isRaw

Type: numeric or string

When set to 1 object names return in the same format as they were defined on the data source. Value can range from 0 to 1. Default value is 0.

Default value: 0

//Set isRaw to 1 to fetch data as specified in the data source.
chartObj.getJSONData({ isRaw: 1});

setJSONData

Sets chart data in the JSON data format. When this function is called on a chart that has already rendered, it immediately updates the chart with the new data. The function can also be used to set data for a new chart.

Note: A preferrable alternative to using this method is to pass chart data to the dataSource attribute of the FroalaCharts constructor.

Note: The setJSONData() function is shorthand for the setChartData() method, where the data format is set to json. So, calling chart.setXMLData({'chart': ...}) is the same as calling chart.setChartData({'chart': ...}, 'json').

Parameters

data

Type: string or object

JSON data to be set for the chart, as a string or as a JavaScript object

setJSONUrl

Fetches chart data from the URL provided, in the JSON format. When this function is called on a chart that has already rendered, it immediately updates the chart with the new data. The function can also be used to set data for a new chart.

Note: A preferrable alternative to using this method is to pass chart data to the dataSource attribute of the Froala Charts constructor.

Note: The setJSONUrl() function is shorthand for the setChartDataUrl() method, where the data format of the URL is set to jsonurl. So, calling chart.setJSONUrl('data.json') is the same as calling chart.setChartDataUrl('data.json', 'jsonurl').

Parameters

url

Type: string

Path to the JSON data file

getCSVData

Fetch chart data set in the CSV format.

The data returned is the closest possible comma-separated value representation that has been provided to the chart. The exported data does not contain any functional or cosmetic attribute that was set on the chart. However, the following chart attributes can be set to customise the CSV output:

Chart Attribute Type Description
exportDataSeparator string Sets the CSV delimiter string. Default: , (comma)
exportDataQualifier string Sets the CSV qualifier string. Default: {quot}
exportDataFormattedVal boolean Sets whether the output will be a formatted string or a pure number
exportErrorColumns boolean Forces error output on the error bar, error line, and error scatter charts

For the exportDataSeparator and exportDataQualifier attributes, you can provide the quotation mark, the apostrophe, and the tab character using the {quot}, {apos} and {tab} short-codes, respectively.

This function needs to be called on an existing chart that has been loaded and has a valid data. If this function is called on a chart which has no data set on it, it returns an empty stringokay.

Note: As of now, the CSV data generator uses heuristic methods to determine the nature of the output because the method does not internally have access to the chart-type being used. As such, when the chart type cannot determined from the data itself, this method falls back to a generic output format.

Note: This function is the shorthand for chart.getChartData('csv').

getDataAsCSV

Fetch chart data as comma-separated values. The delimiter can be changed by passing relevant chart attributes.

render

Renders a chart inside a container element on a page. If the chart is already rendered, it can be re-rendered inside the same container DOM element or a different element.

Creating a chart using new FroalaCharts() only creates a JavaScript instance for the chart; this function is called to render the chart. Usually, the renderAt construction parameter specifies the element on the page, inside which the chart will be rendered. If renderAt is not provided, then the container element is specified as the parameter to this function.

Parameters

containerElement

Type: string or DOMElement

Reference or ID of the DOM element inside which the chart is to be rendered. If this argument is not provided, it is assumed that the renderAt attribute is provided during chart creation.

insertMode

Type: FroalaCharts~DOMInsertModes

Method for inserting the chart's DOM element within the containerElement. Click here to read more about the DOM insert modes.

Default value: replace

callback

Type: FroalaCharts~renderCallback

Callback function executed after the chart is successfully rendered. If the last parameter to the render() function is a function, it is treated as a callback.

resizeTo

Resizes the chart to the specified width and height. The values for the width and height are passed, in pixels or percentage, as parameters to this function. If the function is called without any parameters, it returns the current value of the chart width and height.

This function is useful in controlling the chart dimensions based on changes in the dimensions of a resizable dialog box. It is also useful in resizing charts for responsive layouts, based on device orientation change.

Note: When the chart dimensions are set in percentage, the chart partially redraws itself when the chart container is resized. The chart uses a very low-profile polling, at an interval of 300 ms to check whether the container has effectively resized.

Parameters

width

Type: number or percent

Chart width to set, in pixels or percentage

height

Type: number or percent

Chart height to set, in pixels or percentage

dispose

Disposes a chart completely, when called on an instance of FroalaCharts. This clears the entire chart object and removes it from the DOM tree structure. When the chart is successfully disposed, chartInstance.disposed is set to true.

configure

Configures status messages that are displayed while rendering a chart. For example, while a chart’s data is being fetched from a remote URL, the chart will display the message Retrieving data. Please wait.

Parameters

option

Type: FroalaCharts~chartStatusMessages

To configure a single attribute, specify the attribute (the key) as a string. To configure multiple attributes, this can be an object having key-value pairs of all configuration options.

value

Type: string

If the option parameter has a single value as the key, this parameter is the value of that key.

render

static function

Uses a one-line argument parameter to render FroalaCharts directly into the container specified in the arguments.

Calling this function directly is same as creating a new instance of FroalaCharts and calling .render() on it. For example, var chart = FroalaCharts.render({...}); is same as var chart = new FroalaCharts({...}); ... chart.render();.

Parameters

options

Type: object

Chart configuration options required to create a chart. The options must include the renderAt parameter for the chart to render instantly.

callback

Type: FroalaCharts~renderCallback

Callback function executed when the chart is successfully rendered

Example

FroalaCharts.ready(function () {
    var chart = FroalaCharts.render({
        type: "column",
        renderAt: "chart-container-div",
        dataSource: "data.json",
        dataFormat: "jsonurl"
    });
});

setBinning

Overrides the binning rules followed by the chart with the binning rules provided to this API. If some time unit is missing from the input binning rules, then the default multipliers for that time unit will be used by the chart. If any incorrect multipliers are provided to a unit, they will be ignored.

//DataStore: In-browser store of tabular data
    var dataStore = new FroalaCharts.DataStore();
    new FroalaCharts({
        type: "timeseries",
        renderAt: "container",
        id: "binning-API-methods",
        width: "100%",
        height: 600,
        dataSource: {
          caption: {
            text: "Sales Analysis"
          },
          subcaption: {
            text: "Grocery"
          },
          yAxis: [{
            plot: {
              value: "Grocery Sales Value",
              "type": "column"
            },
            format: {
              prefix: "$"
            },
            title: "Sale Value"
          }],
//Fetch the data and schema to create the DataTable
          data: dataStore.createDataTable(data, schema)
        }
    
      }).render()
    })
    
//Set Binning Method
    document.getElementById("setBin").addEventListener("click", function() {
     FroalaCharts.items["binning-API-methods"].setBinning({
        "year": [1],
        "month": [2],
        "day": [2],
        "minute": []
      })
      document.getElementById("showMessage").innerHTML = "Current bin is now set to 1-year, 2-months & 2-day";
    });
    
//Get Binning Method
    document.getElementById("getBin").addEventListener("click", function() {
    
      var bin =FroalaCharts.items["binning-API-methods"].getBinning();
      document.getElementById("showMessage").innerHTML = "Current Bin : " +
        bin.year + "-" + "year" + ((bin.year == 1) ? " " : "s") + ", " +
        bin.month + "-" + "month" + ((bin.month == 1) ? " " : "s") + " & " +
        bin.day + "-" + "day" + ((bin.day == 1) ? " " : "s");
    
    });

setBinning Parameters

Name Type Description Default Value
millisecond number

All the multipliers applicable for the millisecond unit.

second number

All the multipliers applicable for the second unit.

minute number

All the multipliers applicable for the minute unit

hour number

All the multipliers applicable for the hour unit.

day number

All the multipliers applicable for the day unit.

month number

All the multipliers applicable for the month unit.

year number

All the multipliers applicable for the year unit.

getBinning

Returns the binning rules that are being followed by the chart. If any custom binning rules are in effect, the returned rules will take into account the modifications made by them as well.

//DataStore: In-browser store of tabular data
    var dataStore = new FroalaCharts.DataStore();
    new FroalaCharts({
        type: "timeseries",
        renderAt: "container",
        id: "binning-API-methods",
        width: "100%",
        height: 600,
        dataSource: {
          caption: {
            text: "Sales Analysis"
          },
          subcaption: {
            text: "Grocery"
          },
          yAxis: [{
            plot: {
              value: "Grocery Sales Value",
              "type": "column"
            },
            format: {
              prefix: "$"
            },
            title: "Sale Value"
          }],
//Fetch the data and schema to create the DataTable
          data: dataStore.createDataTable(data, schema)
        }
    
      }).render()
    })
    
//Set Binning Method
    document.getElementById("setBin").addEventListener("click", function() {
     FroalaCharts.items["binning-API-methods"].setBinning({
        "year": [1],
        "month": [2],
        "day": [2], //DataStore: In-browser store of tabular data
    var dataStore = new FroalaCharts.DataStore();
    new FroalaCharts({
        type: "timeseries",
        renderAt: "container",
        id: "binning-API-methods",
        width: "100%",
        height: 600,
        dataSource: {
          caption: {
            text: "Sales Analysis"
          },
          subcaption: {
            text: "Grocery"
          },
          yAxis: [{
            plot: {
              value: "Grocery Sales Value",
              "type": "column"
            },
            format: {
              prefix: "$"
            },
            title: "Sale Value"
          }],
    //Fetch the data and schema to create the DataTable
          data: dataStore.createDataTable(data, schema)
        }
    
      }).render()
    })
    
    //Set Binning Method
    document.getElementById("setBin").addEventListener("click", function() {
     FroalaCharts.items["binning-API-methods"].setBinning({
        "year": [1],
        "month": [2],
        "day": [2],
        "minute": []
      })
      document.getElementById("showMessage").innerHTML = "Current bin is now set to 1-year, 2-months & 2-day";
    });
    
    //Get Binning Method
    document.getElementById("getBin").addEventListener("click", function() {
    
      var bin =FroalaCharts.items["binning-API-methods"].getBinning();
      document.getElementById("showMessage").innerHTML = "Current Bin : " +
        bin.year + "-" + "year" + ((bin.year == 1) ? " " : "s") + ", " +
        bin.month + "-" + "month" + ((bin.month == 1) ? " " : "s") + " & " +
        bin.day + "-" + "day" + ((bin.day == 1) ? " " : "s");
    
    });
        "minute": []
      })
      document.getElementById("showMessage").innerHTML = "Current bin is now set to 1-year, 2-months & 2-day";
    });
    
//Get Binning Method
    document.getElementById("getBin").addEventListener("click", function() {
    
      var bin =FroalaCharts.items["binning-API-methods"].getBinning();
      document.getElementById("showMessage").innerHTML = "Current Bin : " +
        bin.year + "-" + "year" + ((bin.year == 1) ? " " : "s") + ", " +
        bin.month + "-" + "month" + ((bin.month == 1) ? " " : "s") + " & " +
        bin.day + "-" + "day" + ((bin.day == 1) ? " " : "s");
    
    });

getBinning Returned Values

Name Type Description Default Value
millisecond number

All the multipliers applicable for the millisecond unit.

second number

All the multipliers applicable for the second unit.

minute number

All the multipliers applicable for the minute unit

hour number

All the multipliers applicable for the hour unit.

day number

All the multipliers applicable for the day unit.

month number

All the multipliers applicable for the month unit.

year number

All the multipliers applicable for the year unit.

setCurrentBin

Sets the provided unit and multiplier as the current binning in the chart by adjusting spread of time on the focus canvases. The provided multiplier must be a valid multiplier for the given time unit (as per the currently active binning rules in the chart). If it is not, then there is no visible effect of calling this method. If the multiplier is not provided, it is assumed to be 1. If the unit is not provided, there should be no visible effect of calling this method.

 //DataStore: In-browser store of tabular data
var dataStore = new FroalaCharts.DataStore();
var ftChart = new FroalaCharts({
type: "timeseries",
          renderAt: "container",
          width: 800,
          height: 500,
          dataSource: {
            caption: {
              text: "Sales Analysis"
            },
            subcaption: {
              text: "Grocery"
            },
            yAxis: [{
              plot: {
                value: "Grocery Sales Value",
                "type": "column"
              },
              format: {
                prefix: "$"
              },
              title: "Sale Value"
            }],
            // Fetch the data and schema to create the DataTable
            data: dataStore.createDataTable(data, schema)
          }
        }).render();
       //getBin() fetches the current Bin for the chart
        function getBin() {
          var bin = ftChart.getCurrentBin();
          document.getElementById("showMessage").innerHTML = "Current Bin : " + bin.multiplier + " " + bin.unit + ((bin.multiplier == 1) ? "" : "s");
        };
       //setBin3() sets the multiplier to 3 for the chart
        function setBin3() {
          ftChart.setCurrentBin({
            "unit": "day",
            "multiplier": "3"
          });
          document.getElementById("showMessage").innerHTML = "Current bin is now set to 3 days";
        };
       //setBin5() sets the multiplier to 5 for the chart
        function setBin5() {
          ftChart.setCurrentBin({
            "unit": "day",
            "multiplier": "5"
          });
          document.getElementById("showMessage").innerHTML = "Current bin is now set to 5 days";
        };
        document.getElementById("getBin").addEventListener("click", getBin);
        document.getElementById("setBin3").addEventListener("click", setBin3);
        document.getElementById("setBin5").addEventListener("click", setBin5);
      });

setCurrentBin Parameters

Name Type Description Default Value
unit string

The unit of time to be represented in each bin - millisecond, second, minute, hour, day, month or year.

multiplier number

The multiplier for the unit to be represented in each bin.

getCurrentBin

Provides information about the binning applied in the chart when the method was invoked.

//DataStore: In-browser store of tabular data
var dataStore = new FroalaCharts.DataStore();
var ftChart = new FroalaCharts({
          type: "timeseries",
          renderAt: "container",
          width: 800,
          height: 500,
          dataSource: {
            caption: {
              text: "Sales Analysis"
            },
            subcaption: {
              text: "Grocery"
            },
            yAxis: [{
              plot: {
                value: "Grocery Sales Value",
                "type": "column"
              },
              format: {
                prefix: "$"
              },
              title: "Sale Value"
            }],
            // Fetch the data and schema to create the DataTable
            data: dataStore.createDataTable(data, schema)
          }
        }).render();
       //getBin() fetches the current Bin for the chart
        function getBin() {
          var bin = ftChart.getCurrentBin();
          document.getElementById("showMessage").innerHTML = "Current Bin : " + bin.multiplier + " " + bin.unit + ((bin.multiplier == 1) ? "" : "s");
        };
       //setBin3() sets the multiplier to 3 for the chart
        function setBin3() {
          ftChart.setCurrentBin({
            "unit": "day",
            "multiplier": "3"
          });
          document.getElementById("showMessage").innerHTML = "Current bin is now set to 3 days";
        };
       //setBin5() sets the multiplier to 5 for the chart
        function setBin5() {
          ftChart.setCurrentBin({
            "unit": "day",
            "multiplier": "5"
          });
          document.getElementById("showMessage").innerHTML = "Current bin is now set to 5 days";
        };
        document.getElementById("getBin").addEventListener("click", getBin);
        document.getElementById("setBin3").addEventListener("click", setBin3);
        document.getElementById("setBin5").addEventListener("click", setBin5);
      });

getCurrentBin Returned Values

Name Type Description Default Value
unit string

The unit of time to be represented in each bin - millisecond, second, minute, hour, day, month or year.

multiplier number

The multiplier for the unit to be represented in each bin.

setTimeSelection

Updates the start and end time of the time selection on the focus canvases. This will also result in a change across all of the chart’s components accordingly.

 //DataStore: In-browser store of tabular data
	var dataStore = new FroalaCharts.DataStore();
var ftChart = new FroalaCharts({
      type: "timeseries",
      renderAt: "container",
      width: 800,
      height: 550,
      dataSource: {
        chart: {},
        caption: {
          text: "Daily Visitors Count of a Website"
        },
        yAxis: [{
          plot: {
            value: "Daily Visitors",
            type: "smooth-area"
          },
          title: "Daily Visitors Count",
          format: {
            suffix: "k"
          }
        }],
      // Fetch the data and schema to create the DataTable
        data: dataStore.createDataTable(data, schema)
      }
    }).render();

  // getSelection() fetches the start and end time
    function getSelection() {
      var s = new Date(ftChart.getTimeSelection().start);
      var e = new Date(ftChart.getTimeSelection().end);
      document.getElementById("test").style.display = "none";
      document.getElementById("setMessage").innerHTML = "Current selection range : " + s.getDate() + "/" + (s.getMonth()+1) + "/" + s.getFullYear() + " to " + e.getDate() + "/" + (e.getMonth()+1) + "/" + e.getFullYear();
    };
   //setSelection() sets the start and end time
    function setSelection() {
      document.getElementById("setMessage").innerHTML = "Select a range from the above range picker";
      document.getElementById("test").style.display = "inline";
      $(function() {
      var smoment = moment([2016, 0, 1]);
      var emoment = moment([2018, 11, 12]);
      $("input[name="daterange"]").daterangepicker({
        opens: "left",
        startDate: smoment,
        endDate: emoment
      }, function(start, end, label) {

        var s = new Date([start.format("YYYY"), start.format("MM"), start.format("DD")]);
        var e = new Date([end.format("YYYY"), end.format("MM"), end.format("DD")]);

        ftChart.setTimeSelection({
          end: s.getTime(),
          start: e.getTime()
        });

      });
    });
    };
    document.getElementById("getSelection").addEventListener("click", getSelection);
    document.getElementById("setSelection").addEventListener("click", setSelection);

  }) }

setTimeSelection Parameters

Name Type Description Default Value
start string

The UNIX timestamp corresponding to the time at which to start the time selection visible on the focus canvases.

end number

The UNIX timestamp corresponding to the time at which to end the time selection visible on the focus canvases.

getTimeSelection

Provides start and end UNIX timestamps of the visible window of the time axis.

 //DataStore: In-browser store of tabular data
var dataStore = new FroalaCharts.DataStore();
var ftChart = new FroalaCharts({
      type: "timeseries",
      renderAt: "container",
      width: 800,
      height: 550,
      dataSource: {
        chart: {},
        caption: {
          text: "Daily Visitors Count of a Website"
        },
        yAxis: [{
          plot: {
            value: "Daily Visitors",
            type: "smooth-area"
          },
          title: "Daily Visitors Count",
          format: {
            suffix: "k"
          }
        }],
      // Fetch the data and schema to create the DataTable
        data: dataStore.createDataTable(data, schema)
      }
    }).render();

  // getSelection() fetches the start and end time
    function getSelection() {
      var s = new Date(ftChart.getTimeSelection().start);
      var e = new Date(ftChart.getTimeSelection().end);
      document.getElementById("test").style.display = "none";
      document.getElementById("setMessage").innerHTML = "Current selection range : " + s.getDate() + "/" + (s.getMonth()+1) + "/" + s.getFullYear() + " to " + e.getDate() + "/" + (e.getMonth()+1) + "/" + e.getFullYear();
    };
   //setSelection() sets the start and end time
    function setSelection() {
      document.getElementById("setMessage").innerHTML = "Select a range from the above range picker";
      document.getElementById("test").style.display = "inline";
      $(function() {
      var smoment = moment([2016, 0, 1]);
      var emoment = moment([2018, 11, 12]);
      $("input[name="daterange"]").daterangepicker({
        opens: "left",
        startDate: smoment,
        endDate: emoment
      }, function(start, end, label) {

        var s = new Date([start.format("YYYY"), start.format("MM"), start.format("DD")]);
        var e = new Date([end.format("YYYY"), end.format("MM"), end.format("DD")]);

        ftChart.setTimeSelection({
          end: s.getTime(),
          start: e.getTime()
        });

      });
    });
    };
    document.getElementById("getSelection").addEventListener("click", getSelection);
    document.getElementById("setSelection").addEventListener("click", setSelection);

  }) }

getTimeSelection Returned Values

Name Type Description Default Value
start string

The UNIX timestamp corresponding to the time at which to start the time selection visible on the focus canvases.

end number

The UNIX timestamp corresponding to the time at which to end the time selection visible on the focus canvases.

resizeTo

Resizes the chart to the specified width and height. The values for the width and height are passed, in pixels or percentage, as parameters to this function. If the function is called without any parameters, it returns the current value of the chart width and height.

This function is useful in controlling the chart dimensions based on changes in the dimensions of a resizable dialog box. It is also useful in resizing charts for responsive layouts, based on device orientation change.

Note: When the chart dimensions are set in percentage, the chart partially redraws itself when the chart container is resized. The chart uses a very low-profile polling, at an interval of 300 ms to check whether the container has effectively resized.

            FroalaCharts.ready(function() {
                var myChart = new FroalaCharts({
				type: "timeseries",
                            renderAt: "container",
                    width: "100%",
                    height: 400,
                    id: "chart1",
                    dataSource: {}
                }).render();
            
                //Resize the chart
                myChart.resizeTo("100%", "500");
            });

resizeTo Parameters

Name Type Description Default Value
width number/percent

Chart width to set, in pixels or percentage

height number/percent

Chart height to set, in pixels or percentage

lockResize

Allows users to controls whether the chart will be dynamically resizable or not when rendered using percent height and width.

                FroalaCharts.ready(function() {
		var myChart = new FroalaCharts({
                        type: "timeseries",
                        renderAt: "container",
                        width: "100%",
                        height: 400,
                        id: "chart1",
                        dataSource: {}
                    }).render();
                ​
                    //Locking the automatic percentage-based resizing. If resize is already locked, sending false unlocks it.
                    myChart.lockResize(true);
                });

lockResize Parameters

Name Type Description Default Value
state boolean

Setting this parameter to true will lock the automatic percentage-based resizing. If resize is already locked, sending false unlocks it.

getSVGString

Returns the SVG string of a chart. This function can be called only after the chart has rendered.

FroalaCharts.ready(function () {
    var myChart = new FroalaCharts({
    type: "timeseries",
    renderAt: "container",
    width: "450",
    height: "350",
    dataSource: {
      data: froalaTable,
      chart: {
      exportEnabled: 1
      },
      caption: {
        text: "Online Sales of a SuperStore in the US"
      },
      yAxis: {
        "plot": {
          "value": "Sales",
          "type": "line"
        },
      }
    }
  }).render();
//Returns the SVG string of the chart
  function svgString() {

				myChart.getSVGString(function(svg){
        	document.getElementById("msg").appendChild(        document.createTextNode(svg));
				});

    }
    document.getElementById("get").addEventListener("click", svgString);
  })
});

getSVGString Parameters

Name Type Description Default Value
callBackFN( svgString ) getSVGString-callBack

callBackFN is called only when getSVGString() completes its execution.

keepImages keepImages

To get the images present in the chart from the SVG string, set the parameter of keepImages object to 1.

batchExport

Exports multiple charts in a single image. This method either takes no arguments or takes an object as an argument.

//batchExport exports multiple charts in a single image
	 batchExportConfig1 = function() {
FroalaCharts.batchExport({
    "charts": [{
      "id": "chart1",
    }],
    "exportFileName": "batchExport",
    "exportFormat": "jpg",
    "exportAtClientSide": "1"
  })
}

FroalaCharts.ready(function () {
    var myChart = new FroalaCharts({
    type: "timeseries",
    id: "chart1",
    renderAt: "container",
    width: "450",
    height: "350",
    dataSource: {
      data: froalaTable,
      chart: {
      exportEnabled: 1
      },
      caption: {
        text: "Online Sales of a SuperStore in the US"
      },
      yAxis: {
        "plot": {
          "value": "Sales",
          "type": "line"
        },
      }
    }
  }).render();

  })
});

batchExport Parameters

Name Type Description Default Value
imageWidth number

Width of the exported image (of the charts)

Maximum chart width + 10
imageHeight number

Height of the exported image (of the charts)

(Total height of all charts + 5) * (number of charts + 1)
charts object

The configuration required for the chart(s) being exported can be provided in this object using the attributes given below:

charts.id string

Valid Froala Charts ID, to attach the chart on the main image

charts.x number

x-coordinate for positioning the exported image

5
charts.y number

y-coordinate for positioning the exported image

previous chart's y-coordinate + 5
charts.width number

Custom width for the exported image

Note: If only one value from the width and the height of the chart is provided, the value of the other is calculated in a way that the aspect ratio is maintained.

Current chart width
charts.height number

Custom height for the exported image

Note: If only one value from the width and the height of the chart is provided, the value of the other is calculated in a way that the aspect ratio is maintained.

Current chart height
background object

The configuration required for the exported image's background can be provided in this object using the attributes given below:

background.bgColor hexcolor

Background color for the exported image

#ffffff
background.bgImage string

Background image for the exported images

background.bgImageAlpha number

Transparency of the background image

background.bgImageX number

Starting x-coordinate for positioning the background image

background.bgImageY number

Starting y-coordinate for positioning the background image

background.bgImageWidth number

Width of the background image

Note: If only one value from the width and the height is provided, the value of the other is calculated in a way that the aspect ratio is maintained.

Original width of the image
background.bgImageHeight number

Height of the background image

Note: If only one value from the width and the height is provided, the value of the other is calculated in a way that the aspect ratio is maintained.

Original height of the image
exportTargetWindow string

Set to _self to open the exported image in the same window

Set to _blank to open the exported image in a new window

_self
exportAction string

Set to _save to save the exported image on the server

Set to _download to send back the image to the client as a download

_download
exportFileName string

Default file name (excluding the extension) for the exported image

exportHandler string

For server-side exporting: Path of the export handler (the ready-to-use scripts provided by Timeseries)

For client-side exporting: DOM ID of the Timeseries Export Component embedded in the web page, along with the chart

_download
exportFormats string

List of formats in which the chart can be exported

The formats are separated using the | (pipe) character.

_download
exportCallback string

Name of the JavaScript function that is called when the export process finishes

exportAtClientSide string

Set to 1 to enable client-side exporting

_download

getChartData

Fetches the data set when a chart has been rendered.

               <select id="data_format">
                    <option value="csv">CSV</option>
                    <option value="json">JSON</option>
                </select>
              FroalaCharts.ready(function() {
           var myChart = new FroalaCharts({
               type: "timeseries",
               renderAt: "container",
               width: "100%",
               height: 400,
               id: "chart1",
               dataSource: {}
           }).render();
       
       var format = document.getElementById("data_format").value;
       //getChartData fetches the data set for a chart
       var data = FroalaCharts.getChartData(format);
       }

getChartData Parameters

Name Type Description Default Value
format dataFormats

Format in which chart data has to be retrieved

setChartData

Sets the data for a chart.

When this function is called on a chart that is already rendered, the chart is instantly updated with the new data. When it is used to set data for a chart before it has rendered, data is initially stored internally and is passed to the chart when it is rendered.

Note: A preferrable alternative to using the setChartData() method is to pass chart data to the dataSource attribute of the Timeseries constructor.

var year_2018 = {
	//Enter data for year 2018
	}

var year_2019 ={
	//Enter data for year 2019
}
FroalaCharts.ready(function() {
	var myChart = new FroalaCharts({
		type: "timeseries",
    	renderAt: "container",
		width: "100%",
		height: 400,
		id: "chart1",
		dataSource: {

		}
	}).render();

 var year_data = document.getElementById("year").value;
    if (year_data == "2018")
//setChartData sets the data for a chart
    	myChart.setChartData(year_2018, "json");
   			else if (year_data =="2019")
   				myChart.setChartData(year_2019, "json");
});

setChartData Parameters

Name Type Description Default Value
data string/object

Data to be passed to the chart

format dataFormats

Format of the data being passed. If the value for this parameter is not a valid dataFormat, then the default or previously set data format is assumed.

Note: If the data format is already known, then the setJSONData() or the setXMLData() methods can be used.

getChartAttribute

Fetches value of chart attributes explicitly applied to the root chart object (or the <chart> node element).

 FroalaCharts.ready(function() {
            var myChart = new FroalaCharts({
			type: "timeseries",
                renderAt: "container",
                width: "100%",
                height: 400,
                id: "chart1",
                dataSource: {}
            }).render();
        
        document.getElementById("chart1").innerHTML = "Current theme: " + myChart.getChartAttribute("theme");
        
        //getChartAttribute fetches the value of chart attribute explicitly
          function getAtt() {
        
               var select = document.getElementById("chart1");
               myChart.setChartAttribute("theme", select.value);
         document.getElementById("current_value").innerHTML = "Current theme: " + myChart.getChartAttribute("theme");
        
            }
            document.getElementById("theme-type").addEventListener("change", getAtt);
        });

getChartAttribute Parameters

Name Type Description Default Value
attribute string/array

To fetch the value of a single attribute, pass the attribute name as a string. For multiple attributes, pass an array of attribute names. Values will be returned in the order of the attribute names in the array.

setChartAttribute

Updates a chart's attributes with a new attribute-value pair, thus updating the chart's data definition root (the <chart> node in the XML data or the chart object in the JSON data).

FroalaCharts.ready(function() {
        var myChart = new FroalaCharts({
		type: "timeseries",
            renderAt: "container",
            width: "100%",
            height: 400,
            id: "chart1",
            dataSource: {
            }
        }).render();
    
    //setChartAttribute updates the chart's attributes with new attribute-value
     function setAtt() {
           var select = document.getElementById("chart1");
           myChart.setChartAttribute("theme", select.value);
    
    
        }
    
        document.getElementById("chart1").addEventListener("change", setAtt);
    
    });  

setChartAttribute Parameters

Name Type Description Default Value
attributes object/string

To set/update multiple attributes at once, an object containing all the key-value pairs is passed. In case of a single value, a string that is the key (the attribute name) is passed.

value string

If the attributes parameter is a single string value, the value parameter contains the value for that key.

addEventListener

Used to attach an event to the chart.

    FroalaCharts.ready(function() {
        var myChart = new FroalaCharts({
            type: "timeseries",
            renderAt: "container",
            width: "100%",
            height: 400,
            id: "chart1",
            dataSource: {  
                }
        }).render();
    //attaching an event to the chart using addEventListener()
        myChart.addEventListener("dataPlotClick", "onDataPlotClick");
        });

addEventListener Parameters

Name Type Description Default Value
type string/array

Type (name) of the event to listen to. To register the listener for multiple events in the same registration call, provide all event names as an array.

listener eventListener

Function to be exceuted when the event is triggered. If multiple listeners are bound to an event, the listeners are executed in the order of definition, with arguments specific to the triggered event.

removeEventListener

Used to remove an event attached to the chart.

FroalaCharts.ready(function() { var myChart = new FroalaCharts({ type: "timeseries", renderAt: "container", width: "100%", height: 400, id: "chart1", dataSource: {} }).render(); //removing an event attached to the chart myChart.removeEventListener("dataPlotClick", "onDataPlotClick"); });

removeEventListener Parameters

Name Type Description Default Value
type string/array

Type (name) of the event whose listener(s) has to be removed

listener function

Listener function to remove

getObjectReference

Return the DOM element created by Timeseries in which charts will be rendered <span>

FroalaCharts.ready(function() {
    var myChart = new FroalaCharts({
        id: "chart_1",
        type: "timeseries",
        renderAt: "chart-container",
        width: "90%",
        height: 490,
        dataSource: {
            data: froalaTable,
            chart: {
                exportEnabled: 1
            },
            caption: {
                text: "Online Sales of a SuperStore in the US"
            },
            yAxis: {
                "plot": {
                    "value": "Sales",
                    "type": "line"
                },
            }
        }
    }).render();
    //replaceSVG() replaces the SVG element
    function replaceSVG() {
        var chart = FroalaCharts.getObjectReference("chart_1");
        chart.innerHTML = "<span class="
        rep_text ">The svg element of the chart is replaced by this text</span>";
    }
    //reDrawSVG() redraws the chart
    function reDrawSVG() {
        myChart.render();
    }
    document.getElementById("get_ref").addEventListener("click", replaceSVG);
    document.getElementById("redraw").addEventListener("click", reDrawSVG);

});

getObjectReference Parameters

Name Type Description Default Value
id string

ID of the chart, whose DOMElement is to be referenced.

clone

Creates a copy of a chart instance, creating a new chart with identical construction properties of the chart being cloned. The cloned chart, assigned an auto-generated ID, is rendered in a container DOM element that is explicitly provided.

FroalaCharts.ready(function() {
    var myChart = new FroalaCharts({
        type: "timeseries",
        renderAt: "chart-container",
        width: "90%",
        height: 490,
        dataSource: {
            data: froalaTable,
            chart: {
                exportEnabled: 1
            },
            caption: {
                text: "Online Sales of a SuperStore in the US"
            },
            yAxis: {
                "plot": {
                    "value": "Sales",
                    "type": "line"
                },
            }
        }
    }).render();
    //exact_copy() creates a copy of the chart
    function exact_copy() {
        var cloned_chart = myChart.clone();
        console.log(cloned_chart);
        cloned_chart.render("cloned-chart-container");
    }
    document.getElementById("exact_copy").addEventListener("click", exact_copy);

});

clone Parameters

Name Type Description Default Value
overrides object

Object containing instructions for changes in the cloned chart. For example, passing pieChart.clone({type: 'column'}); will clone the pie chart, but set its chart-type as column. It accepts all the construction parameters of a new Timeseries instance.

argsOnly boolean

Set to true, if a new FroalaCharts object is not required. In that case, it causes the function to return a serializable object that can later be passed to create a new Timeseries instance, and therefore, create a clone.

false

ready

Accepts a function as an argument and that is executed by Timeseries when the page is ready (library loaded, DOM elements rendered).

 //ready() checks if the library is loaded and DOM elements are rendered
 function ready() {
 var rend = document.getElementById("render");
     rend.hidden = false;
     rend.addEventListener("click", renderChart);


     function renderChart() {
         var myChart = new FroalaCharts({
             type: "timeseries",
             renderAt: "chart1",
             width: "90%",
             height: 490,
             dataSource: {
                 data: froalaTable,
                 chart: {
                     exportEnabled: 1
                 },
                 caption: {
                     text: "Online Sales of a SuperStore in the US"
                 },
                 yAxis: {
                     "plot": {
                         "value": "Sales",
                         "type": "line"
                     },
                 }
             }
         }).render();

     }
 }

ready Parameters

Name Type Description Default Value
readyCallback readyCallback

Callback function executed when the Timeseries framework is ready

args *

Argument to be passed to the callback function

FroalaCharts
context function

To execute a function, passed using the fn parameter, in a different scope than the default FroalaCharts scope, pass the appropriate class object here.

FroalaCharts

dataReady

Determines whether a chart will render properly with the data set and returns true or false.

FroalaCharts.ready(function() {
	var year_2016 = {
    //Enter data for year 2016
}
var year_2017 = {
    //Enter data for year 2017
}
var year_2018 = {
    //Enter data for year 2018
}
var year_2019 = {
    //Enter data for year 2019
}
var myChart = new FroalaCharts({
    type: "timeseries",
    renderAt: "container",
    width: "100%",
    height: 400,
    id: "chart1",
    dataSource: year_2018
});

function render() {
    var data = document.getElementById("data").value;

    if (data == "2016") {
        myChart.setChartData(year_2016);
    } else if (data == "2017") {
        myChart.setChartData(year_2017);
    } else if (data == "2018") {
        myChart.setChartData(year_2018);
    } else if (data == "2019") {
        myChart.setChartData(year_2019);
    }

    myChart.render();
    var flag = myChart.dataReady();
    var msg = document.getElementById("msg");
    if (flag) {
        msg.innerHTML = "Data valid. Scroll down to view the chart.";
    } else {
        msg.innerHTML = "Data invalid";
    }
}

document.getElementById("rend").addEventListener("click", render);
});
});

dataReady Parameters

Name Type Description Default Value
available boolean

Setting this parameter to true returns the status of the data, irrespective of its compatibility with the chart type. In that case, this function will return false if data provided to the chart triggers the dataLoadError or dataInvalid events

false

hasRendered

Returns true if the chart has rendered successfully, false if it has not.

FroalaCharts.ready(function() {
    var myChart = new FroalaCharts({
	type: "timeseries",
        renderAt: "chart-container",
        width: "90%",
        height: 490,
        dataSource: {
            data: froalaTable,
            chart: {
                exportEnabled: 1
            },
            caption: {
                text: "Online Sales of a SuperStore in the US"
            },
            yAxis: {
                "plot": {
                    "value": "Sales",
                    "type": "line"
                },
            }
        }
    });

    var msg = document.getElementById("render_status");
    var flag = myChart.hasRendered();
    //to check whether the chart has rendered or not
    if (!flag) {
        msg.innerHTML = "Chart not rendered";

    }

    function render() {
        myChart.render();
        msg.innerHTML = "Chart rendered";
    }

    document.getElementById("render").addEventListener("click", render);

});

print

Prints individual charts. It hides all elements on a page except the chart to print and then invokes the page printing function (window.print()).

FroalaCharts.ready(function() {
    var myChart = new FroalaCharts({
        type: "timeseries",
        renderAt: "chart-container",
        width: "90%",
        height: 490,
        dataSource: {
            data: froalaTable,
            chart: {
                exportEnabled: 1
            },
            caption: {
                text: "Online Sales of a SuperStore in the US"
            },
            yAxis: {
                "plot": {
                    "value": "Sales",
                    "type": "line"
                },
            }
        }
    }).render();
    //print() invokes the page printing function to print the chart
    function print() {
        myChart.print();
    }
    document.getElementById("print").addEventListener("click", print);

});

print Parameters

Name Type Description Default Value
options object

Object containing the printing options configured

options.hideButtons boolean

Hides all buttons on the chart

true

exportChart

Exports a chart as an image or as a PDF document.

FroalaCharts.ready(function() {
	var myChart = new FroalaCharts({
    type: "timeseries",
    renderAt: "container",
    width: "90%",
    height: 490,
    dataSource: {
        data: froalaTable,
        chart: {
            exportEnabled: 1
        },
        caption: {
            text: "Online Sales of a SuperStore in the US"
        },
        yAxis: {
            "plot": {
                "value": "Sales",
                "type": "line"
            },
        }
    }
}).render();
//export_chart() exports the chart as a pdf or image
function export_chart() {
    var format = document.getElementById("format").value;
    myChart.exportChart({
        "exportFormat": format
    });
}
document.getElementById("export").addEventListener("click", export_chart);
});
});

exportChart Parameters

Name Type Description Default Value
options object

The exportChart method takes the following parameters:

options.exportFormat string

A chart can be exported in one of the following formats:

| Export Format | Description |

| --------- | :-------------|

| png| Exports the charts in the high quality lossless PNG format |

| jpg | Exports the chart in the high quality JPEG image format |

| pdf | Exports the chart as a PDF document |

png
options.exportFileName string

File name for the chart being exported, excluding the extension. The extension is automatically appended depending on the value of exportFormat parameter.

FroalaCharts
options.exportTargetWindow string

When the exportAction parameter is set to download as , this parameter lets you configure whether the return image or PDF will open in the same window (as an attachment for download), or in a new browser window (_blank).

_self
options.exportHandler string

URL of the export server

options.exportAction string

Specifies whether the exported image will be sent back to the browser as download, or whether it will be saved on to the server.

Action Value Description
download The exported chart image or PDF will be downloaded as file.
save The exported chart will be saved on the server.

For the charts to be saved on the server, you would need to setup your own export handling server.

download
options.exportCallback function

Callback JavaScript function executed when the export process is complete. If this parameter is not assigned a value, then the window.FC_Exported is executed.

FC_Exported

showChartMessage

Shows a text message on a chart.

FroalaCharts.ready(function() {
    var myChart = new FroalaCharts({
	type: "timeseries",
        renderAt: "chart-container",
        width: "90%",
        height: 490,
        dataSource: {
            data: froalaTable,
            chart: {
                exportEnabled: 1
            },
            caption: {
                text: "Online Sales of a SuperStore in the US"
            },
            yAxis: {
                "plot": {
                    "value": "Sales",
                    "type": "line"
                },
            }
        }
    }).render();
    //show() displays a text message on the chart
    function show() {

        var mode = document.getElementById("mode");
        var msg = document.getElementById("chart_message").value.trim();
        if (msg !== "" && mode.selectedIndex !== 0) {
            myChart.render();
            if (mode.value == "onchart") {
                myChart.showChartMessage(msg);
            } else if (mode.value == "overlay") {
                myChart.showChartMessage(msg, true);
            } else if (mode.value == "overlaycan") {
                myChart.showChartMessage(msg, true, true);
            }
        }
    }
    document.getElementById("show_message").addEventListener("click", show);


});

showChartMessage Parameters

Name Type Description Default Value
text string

Text message to be displayed

modal boolean

Boolean value to indicate whether the message will be shown on an overlay button or on the chart.

false
cancelable boolean

If set to true, the modal can be closed by clicking. Defaults to false.

Note: Applicable only if modal is set to true.

false

render

Renders a chart inside a container element on a page. If the chart is already rendered, it can be re-rendered inside the same container DOM element or a different element.

new FroalaCharts({
    type: "timeseries",
    renderAt: "container",
    width: "90%",
    height: 490,
    dataSource: {
        data: froalaTable,
        chart: {
            exportEnabled: 1
        },
        caption: {
            text: "Online Sales of a SuperStore in the US"
        },
        yAxis: {
            "plot": {
                "value": "Sales",
                "type": "line"
            },
        }
    }
}).render(); //render() renders the chart 

render Parameters

Name Type Description Default Value
containerElement string/DOMElement

Reference or ID of the DOM element inside which the chart is to be rendered. If this argument is not provided, it is assumed that the renderAt attribute is provided during chart creation.

insertMode DOMInsertModes

Method for inserting the chart's DOM element within the containerElement. Click here to read more about the DOM insert modes.

replace
callback renderCallback

Callback function executed after the chart is successfully rendered. If the last parameter to the render() function is a function, it is treated as a callback.

Dispose

Disposes a chart completely, when called on an instance of FroalaCharts. This clears the entire chart object and removes it from the DOM tree structure. When the chart is successfully disposed, chartInstance.disposed is set to true.

FroalaCharts.ready(function() {
    var myChart = new FroalaCharts({
        type: "timeseries",
        renderAt: "chart-container",
        width: "90%",
        height: 490,
        dataSource: {
            data: froalaTable,
            chart: {
                exportEnabled: 1
            },
            caption: {
                text: "Online Sales of a SuperStore in the US"
            },
            yAxis: {
                "plot": {
                    "value": "Sales",
                    "type": "line"
                },
            }
        }
    }).render();

    var status = document.getElementById("state");
    var state = myChart.disposed;

    if (state === undefined) {
        status.innerHTML = "false";
    }
    //dis() disposes the chart
    function dis() {
        myChart.dispose();
        status.innerHTML = myChart.disposed;
    }
    document.getElementById("dispose").addEventListener("click", dis);

});

configure

Configures status messages that are displayed while rendering a chart. For example, while a chart's data is being fetched from a remote URL, the chart will display the message Retrieving data. Please wait.

FroalaCharts.ready(function() {
    var myChart = new FroalaCharts({
        type: "timeseries",
        renderAt: "chart-container",
        width: "90%",
        height: 490,
        dataSource: {
            "data": [

            ],
            chart: {
                exportEnabled: 1
            },
            caption: {
                text: "Online Sales of a SuperStore in the US"
            },
            yAxis: {
                "plot": {
                    "value": "Sales",
                    "type": "line"
                },
            }
        }
    });
    //rendering the chart
    function render() {
        //configuring the display message
        myChart.configure({
            "dataEmptyMessage": "No data to load. Please check the data source."
        });
        myChart.render();

    }

    document.getElementById("render").addEventListener("click", render);
});

configure Parameters

Name Type Description Default Value
option chartStatusMessages

To configure a single attribute, specify the attribute (the key) as a string. To configure multiple attributes, this can be an object having key-value pairs of all configuration options.

value string

If the option parameter has a single value as the key, this parameter is the value of that key.

FeedData

Adds data to the chart in real-time.

  // update date
	const getNextRandomDate = d => new Date(new Date(d).getTime() + 1000);
  const fd = (d) => {
      var e = new Date(d.getTime() - (d.getTimezoneOffset()) * 60000).toISOString()
      var f = e.split(".")[0]
      var g = f.split("T")
      var h = g.join(" ")
      return h
  }
  // random data generator
  const randBetween = (min, max) => {
      const ceilMin = Math.ceil(min);

      return (
          Math.floor(Math.random() * (Math.floor(max) - ceilMin + 1)) + ceilMin
      );
  };
  // FroalaCharts data store
  const dataStore = new FroalaCharts.DataStore().createDataTable(data, schema);
  // time series chart instance
  const realtimeChart = new FroalaCharts({
      type: "timeseries",
      renderAt: "chart-container",
      width: "100%",
      height: "600",
      dataSource: {
          data: dataStore,
          yAxis: {
              plottype: "area"
          },
          series: "City"
      }
  });

  let lastTimeStr = data[data.length - 1][0];

  realtimeChart.addEventListener(
      "rendered",
      ({
          sender: realtimeChart
      }) => {
          lastTimeStr = getNextRandomDate(lastTimeStr);
          console.log("new lastTimeStr:", lastTimeStr)
          let newDate = new Date(lastTimeStr);
          console.log("newDate without format:", newDate)
          let formattedNewDate = fd(newDate);
          console.log("new Date first time:", formattedNewDate)

          let incrementor = setInterval(() => {
              console.log("formattedNewDate before randomizing:", formattedNewDate);
              newDate = getNextRandomDate(formattedNewDate);
              formattedNewDate = fd(newDate);

              realtimeChart.feedData([
                  [formattedNewDate, randBetween(13, 45), "Kuala Lumpur"],
                  [formattedNewDate, randBetween(13, 45), "Panama City"]
              ]);
          }, 1000);
      });
  realtimeChart.render();

FeedData Parameters

Name Type Description Default Value
stream string

Real-time data for charts and gauges.

[class^="wpforms-"]
[class^="wpforms-"]
[bws_google_captcha]
<div class="gglcptch gglcptch_v2"><div id="gglcptch_recaptcha_513437079" class="gglcptch_recaptcha"></div> <noscript> <div style="width: 302px;"> <div style="width: 302px; height: 422px; position: relative;"> <div style="width: 302px; height: 422px; position: absolute;"> <iframe src="https://www.google.com/recaptcha/api/fallback?k=6Ld6lNoUAAAAAM626LfCOrnkBFJtYZAKESFCjgv_" frameborder="0" scrolling="no" style="width: 302px; height:422px; border-style: none;"></iframe> </div> </div> <div style="border-style: none; bottom: 12px; left: 25px; margin: 0px; padding: 0px; right: 25px; background: #f9f9f9; border: 1px solid #c1c1c1; border-radius: 3px; height: 60px; width: 300px;"> <textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px !important; height: 40px !important; border: 1px solid #c1c1c1 !important; margin: 10px 25px !important; padding: 0px !important; resize: none !important;"></textarea> </div> </div> </noscript></div>
[class^="wpforms-"]
[class^="wpforms-"]
[bws_google_captcha]
<div class="gglcptch gglcptch_v2"><div id="gglcptch_recaptcha_1945232601" class="gglcptch_recaptcha"></div> <noscript> <div style="width: 302px;"> <div style="width: 302px; height: 422px; position: relative;"> <div style="width: 302px; height: 422px; position: absolute;"> <iframe src="https://www.google.com/recaptcha/api/fallback?k=6Ld6lNoUAAAAAM626LfCOrnkBFJtYZAKESFCjgv_" frameborder="0" scrolling="no" style="width: 302px; height:422px; border-style: none;"></iframe> </div> </div> <div style="border-style: none; bottom: 12px; left: 25px; margin: 0px; padding: 0px; right: 25px; background: #f9f9f9; border: 1px solid #c1c1c1; border-radius: 3px; height: 60px; width: 300px;"> <textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px !important; height: 40px !important; border: 1px solid #c1c1c1 !important; margin: 10px 25px !important; padding: 0px !important; resize: none !important;"></textarea> </div> </div> </noscript></div>
[class^="wpforms-"]
[class^="wpforms-"]
[bws_google_captcha]
<div class="gglcptch gglcptch_v2"><div id="gglcptch_recaptcha_1178398799" class="gglcptch_recaptcha"></div> <noscript> <div style="width: 302px;"> <div style="width: 302px; height: 422px; position: relative;"> <div style="width: 302px; height: 422px; position: absolute;"> <iframe src="https://www.google.com/recaptcha/api/fallback?k=6Ld6lNoUAAAAAM626LfCOrnkBFJtYZAKESFCjgv_" frameborder="0" scrolling="no" style="width: 302px; height:422px; border-style: none;"></iframe> </div> </div> <div style="border-style: none; bottom: 12px; left: 25px; margin: 0px; padding: 0px; right: 25px; background: #f9f9f9; border: 1px solid #c1c1c1; border-radius: 3px; height: 60px; width: 300px;"> <textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px !important; height: 40px !important; border: 1px solid #c1c1c1 !important; margin: 10px 25px !important; padding: 0px !important; resize: none !important;"></textarea> </div> </div> </noscript></div>