Search code examples
javascriptjqueryhtmlcssc3.js

Bootstrap tabs and C3 charts not getting along


I am using Bootstrap navigation tabs and each of the tabs has a chart in it. Whichever tab is loaded upon navigating to the home page, it shows perfectly fine. However, the other charts are all overlapping the other content that is on those pages, such as like this:

enter image description here

I cannot figure out how to get this to display correctly at all times, no matter which bootstrap tab is active.

I checked out this article - C3 chart sizing is too big when initially loaded - and it mentions that sometimes c3 charts display incorrectly when using Bootstrap tabs and such. The suggested fix was to use jQuery(window).trigger('resize');. However, I tried doing this in the console and it didn't fix the tab for me.

Any idea how I can go about fixing this? If I simply click inside of the developer console and then back onto the webpage, the chart resizes itself correctly and adjusts its width and x values in to fit within the div that it's supposed to be displayed in.

Here's the script used to generate the chart:

var chart = c3.generate({
    bindto: '#opened-ports-chart',
    data: {
        columns: <%= @data %>,
        type : 'pie',
        onclick: function (d, i) { console.log("onclick", d, i); },
        onmouseover: function (d, i) { console.log("onmouseover", d, i); },
        onmouseout: function (d, i) { console.log("onmouseout", d, i); }
    },
    legend: {
        position: "right"
    }
});

Solution

  • Solved this by resizing the chart upon Bootstrap tab changes:

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
      chart.resize();
    });