Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get object reference from selector for C3 JS charts

I'm using c3.js for graphing and everything is working as expected.

However, I'd like to access the API from other scripts, that is call resize etc...

if I use:

var chart = c3.generate({ ... });

I can then access the chart object and it's API like:

chart.resize();

However, if I do not have access to the chart object as it's another script I can get the HTML DOM element (using jQuery):

$(".c3").each(function(i, chart) { 
    // Here I want to do something like chart.resize();
    // But chart is just the DOM reference, not the chart variable
    // I need something like c3.get(chart)????
});

But chart in the loop is a DOM object, not the var chart made from c3.generate.

Any ideas how I can get this object? The documentation isn't quite finished ;)

like image 832
RemarkLima Avatar asked Sep 10 '14 12:09

RemarkLima


1 Answers

As you're already using jQuery, here's a solution using jQuery data:

Save a reference to the chart, keyed on its DOM element:

var selector = '#some-selector';
var chart = c3.generate({
  bindTo: selector,
  // ...
});

$(selector).data('c3-chart', chart);

To access the chart for each .c3 element:

$('.c3').each(function() {
  var chart = $(this).data('c3-chart'); 
});
like image 197
joews Avatar answered Oct 16 '22 13:10

joews