How to get object reference from selector for C3 JS charts
Asked Answered
T

1

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

Torrent answered 10/9, 2014 at 12:33 Comment(0)
W
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'); 
});
Waftage answered 10/9, 2014 at 12:52 Comment(3)
Works like a charm, jQuery always has these useful gems!Torrent
@Torrent this is not working for me, I still get a DOM elementDaddylonglegs
Are you adding the chart object to the data? Make sure it's not the selector being added...Torrent

© 2022 - 2024 — McMap. All rights reserved.