7

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 ;)

1 Answer 1

11

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'); 
});
Sign up to request clarification or add additional context in comments.

3 Comments

Works like a charm, jQuery always has these useful gems!
@RemarkLima this is not working for me, I still get a DOM element
Are you adding the chart object to the data? Make sure it's not the selector being added...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.