[Chartjs]-How to retrieve the instance of a chart that is not global

1đź‘Ť

I never use this idea/trick (It’s easier to work with global charts).

Anyway, one option is to put (if) or (Switch Statement) inside the loop:

Chart.helpers.each(Chart.instances, function(instance){
  if (instance.chart.canvas.id === "chart_1") {
    console.log("id:"  + instance.chart.canvas.id +"|" + instance.chart.data.datasets[0].data[1]);
  }
  if (instance.chart.canvas.id === "chart_2") {
     /* do something */
  }
})

In my opnion this code is not “so clean” (For 10 charts). I prefer to use new constructor (Maybe someone else got “cleaner” solution).
Anyway this idea will work fine.

Code example – update chart_1 value

https://www.chartjs.org/docs/latest/developers/api.html#updateconfig

chart_1 Update the dataset value of february from 30 to 50:

var chart_1 = document.getElementById('chart_1');
new Chart(chart_1, {
  // The type of chart we want to create
  type: 'line',
  responsive: true,
  // The data for our dataset
  data: {
    labels: ['January', 'February', 'March'],
    datasets: [{
      label: 'My First dataset',
      backgroundColor: 'rgb(255, 99, 132)',
      borderColor: 'rgb(255, 99, 132)',
      data: [20, 30, 45]
    }]
  },
  // Configuration options go here
  options: {}
});

var chart_2_node = document.getElementById('chart_2');
new Chart(chart_2, {
  // The type of chart we want to create
  type: 'bar',
  responsive: true,
  // The data for our dataset
  data: {
    labels: ['April', 'May', 'June'],
    datasets: [{
      label: 'My Second dataset',
      backgroundColor: 'rgb(22, 22, 22)',
      borderColor: 'rgb(22, 22, 22)',
      data: [0, 10, 5]
    }]
  },
  // Configuration options go here
  options: {}
});

Chart.helpers.each(Chart.instances, function(instance){
  if (instance.chart.canvas.id === "chart_1") {
    console.log("id:"  + instance.chart.canvas.id +" | February before update: " + instance.chart.data.datasets[0].data[1]);
    instance.data.datasets[0].data[1] = 50; // Would update the second dataset's value of 'February' to be 50
    instance.update(); // Calling update now animates the position of February from 30 to 50.
  }
  if (instance.chart.canvas.id === "chart_2") {
     /* do something */
  }
})
<section>
  <h4>chart 1</h4>
  <canvas id="chart_1"></canvas></section>
<section>
  <h4>chart 2</h4>
  <canvas id="chart_2"></canvas>
</section>


<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>

You can use this idea to update any value/option of the chart instance.
Example: change the type from bar to line:

    instance.config.type = "pie";
    instance.update(); //

Leave a comment