Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js render in hidden Bootsrap tab

this is driving me mad, I am using Chart.js in my bootstrap tabs but they will not render because the width is set to zero when the DOM is loaded. I finally found this out after trying and figuring out why my graph was not there!

I've searched online and nothing seemed to fix my issue, can anybody please help me with this, I think I need some script that renders the graph when the tab is selected and succesfully loaded Im using this JS:

var data = [
{
    value: 300,
    color:"#F7464A",
    highlight: "#FF5A5E",
    label: "Red"
},
{
    value: 50,
    color: "#46BFBD",
    highlight: "#5AD3D1",
    label: "Green"
},
{
    value: 100,
    color: "#FDB45C",
    highlight: "#FFC870",
    label: "Yellow"
}
];
var options = {
   responsive : true,
   animation: true,
};

var ctx1 = $("#invest-chart").get(0).getContext("2d");
var invest_chart;
new Chart(ctx1).Doughnut(data,  {
   responsive : true,
   animation: true,
});

Along with this html piece in my tab:

<canvas id="invest-chart"></canvas>

Thanks guys!

like image 795
Boris Kamp Avatar asked Apr 22 '15 19:04

Boris Kamp


Video Answer


2 Answers

You need to call the chart after the tab is shown. Bootstrap provides events on their javascript plugins that you can watch for with a jquery on event.

$('a[href=#chart]').on('shown.bs.tab', function(){
  var data = [
  {
    value: 300,
    color:"#F7464A",
    highlight: "#FF5A5E",
    label: "Red"
  },
  {
    value: 50,
    color: "#46BFBD",
    highlight: "#5AD3D1",
    label: "Green"
  },
  {
    value: 100,
    color: "#FDB45C",
    highlight: "#FFC870",
    label: "Yellow"
  }
 ];
 var options = {
   responsive : true,
   animation: true,
 };
 var ctx1 = $("#invest-chart").get(0).getContext("2d");
 var invest_chart;
 new Chart(ctx1).Doughnut(data,  {
   responsive : true,
   animation: true,
 });
});

http://codepen.io/anon/pen/bdGrKv

like image 73
robert_hamm Avatar answered Oct 19 '22 19:10

robert_hamm


In my case, I found a class named "fade" with conflict with bootstrap one with same name. My solution was rename my css class to "MyFade".

like image 1
LÚSAR Avatar answered Oct 19 '22 18:10

LÚSAR