Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Chart js object from selector

After creating a chart like this (with Chart.js, latest version):

var ctx = $('#graph');
var graph = new Chart(ctx, {
  type: 'line',
  data: someData, 
});

I would like to retrieve the Chart object in another function in order to add some data point to it:

var graph = ???
graph.data.labels.push(1)
graph.data.datasets[0].data.push(10);

How do I get the Chart object?

Thank you in advance!

like image 981
JIN Avatar asked May 16 '17 20:05

JIN


2 Answers

You can just do this:

var graph = Chart.getChart('graph')

Works in v3 - not sure when it was introduced.

like image 96
Bryn Lewis Avatar answered Oct 25 '22 02:10

Bryn Lewis


Perhaps:

 var ctx = $('#graph');
 var graph = new Chart(ctx, {
     type: 'line',
     data: someData, 
 });
 ctx.data('graph', graph);

and later:

 var graph = $('#graph').data('graph');
 graph.data.labels.push(1)
 graph.data.datasets[0].data.push(10);
 graph.update();

 

// //

like image 30
Mario Orlandi Avatar answered Oct 25 '22 01:10

Mario Orlandi