Chartjs-How to change HTML style in ChartOption with if condition?

1👍

When you create your chart with your new Chart(....) statement you get back a chart object that you can manipulate and refresh (using the update() function).

So for example if you want your 0 value bars to be red you can do something like this :

var myBarChart = new Chart(document.getElementById("myChart").getContext("2d")).Bar(ChartData, ChartOptions);

for (var key in myBarChart.datasets[0].bars) {
    if (myBarChart.datasets[0].bars[key].value == 0) {
        // Change 2nd bar to red (display).
        myBarChart.datasets[0].bars[key].fillColor = "rgba(255,0,0,0.7)";
        myBarChart.datasets[0].bars[key].strokeColor = "rgba(255,0,0,1)";
        // Change 2nd bar to red (highlight setting on mouse over)
        myBarChart.datasets[0].bars[key].highlightFill = "rgba(212,10,10,0.7)";
        myBarChart.datasets[0].bars[key].highlightStroke = "rgba(212,10,10,1)";
    }
}

myBarChart.update();

You can see what it looks like in a jsfiddle here.

0👍

You can use scriptable options for this in chart.js v3 like so:

var options = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [0, 19, 0, 0, 0, 0],
      backgroundColor: ctx => (ctx.raw === 0 ? 'red' : 'blue'),
      minBarLength: 10
    }]
  },
  options: {}
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>

Leave a comment