sam360
sam360

Reputation: 1131

Get an instance of AmChart using ID

Is there any way to get an instance of the AmChart using the element Id? This is very useful when writing generic API to work with AmCharts.

<div id="myChart"></div>
<div id="myChart2"></div>
<script>
   function makeChart(id, settings) {
        var ins = AmCharts.getChart(id) ?? //need a way to find the instance
        if (ins) ins.clear();
        AmCharts.makeChart(id,settings);
   }
</script>

Upvotes: 4

Views: 6671

Answers (2)

DavidC
DavidC

Reputation: 704

You can use JS find: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

For example (using ES2015 arrow function):

function getChart(id) {
    return AmCharts.charts.find(c => c.div.id === id)
}

Upvotes: 0

gerric
gerric

Reputation: 2297

You can solve this problem like this:

function getChart(id) {
    var allCharts = AmCharts.charts;
    for (var i = 0; i < allCharts.length; i++) {
        if (id == allCharts[i].div.id) {
            return allCharts[i];
        }
    }
}

Now just call getChart("myChart") and it returns the instance.

Upvotes: 13

Related Questions