Chartjs-How can I change the background colors of a bar chart after it has been created?

1👍

I found the .update() function.

https://www.chartjs.org/docs/latest/developers/updates.html

I just had to add

topClickSourceChart.update();

Funny how it worked sometimes but not others, depending on the size of the window.

// can't move to home.js because the label is dynamic
var topClickSourceChart = new Chart('dashboard-click-source-chart', {
    type: 'bar',
    data: {
      datasets: [
    	  {label: "NONE", data: [14]},{label: "Facebook", data: [10]},{label: "Google", data: [5]},{label: "Reddit", data: [1]},{label: "Twitter", data: [1]},
   	  ]
    },
});
topClickSourceChart.data.datasets[0].backgroundColor = '#4D90C3';
topClickSourceChart.data.datasets[1].backgroundColor = '#866DB2';
topClickSourceChart.data.datasets[2].backgroundColor = '#EA6F98';
topClickSourceChart.data.datasets[3].backgroundColor = '#61BDF6';
topClickSourceChart.data.datasets[4].backgroundColor = '#768BB7';
topClickSourceChart.update();
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.min.js" integrity="sha256-MZo5XY1Ah7Z2Aui4/alkfeiq3CopMdV/bbkc/Sh41+s=" crossorigin="anonymous"></script>

<canvas id="dashboard-click-source-chart" height="200" width="200"></canvas>

Leave a comment