Search code examples
javascriptstyleschart.js

How to change HTML style in ChartOption with if condition?


I am using Chart.js to draw graphs in my site. Problem is, that I need to change style of in graph data if value of data is 0.

For e.g. I have array (array1) which have this data: 0; 0; 0.125; 0; 0; 0;

So this would display chat like this:

enter image description here

Code that generate style is like this:

function MoreChartOptions(){} 
        var ChartData = {
        labels : labelsArray,
        datasets : [{
            fillColor : "rgba(52,152,219,1)",
            strokeColor : "rgba(52,152,219,0.5)",
            pointColor : "rgba(52,152,219,1)",
            markerShape :"circle",
            pointStrokeColor : "rgba(255,255,255,1.00)",
            data : array1,
            },
        ]};
ChartOptions= {canvasBackgroundColor:'rgba(255,255,255,1.00)',spaceLeft:12,spaceRight:12,spaceTop:12, ...

My question is: How to change (if it is possible) ChartOptions style (font size - inGraphDataFontSize:12) if value of chart data is 0?

I have try this, but it is not working:

ChartOptions=
{canvasBackgroundColor:'rgba(255,255,255,1.00)', ...
...,
for(a=0;a<array1.length;a++){array1[a] != 0 ? inGraphDataFontSize:12 : inGraphDataFontSize:5}, ...

Realy thanks for help.


Solution

  • 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.