[Chartjs]-How to display chart.js legend with different bar color

1👍

Seeing that you have modified the library code to generate different colors using your own function, you can use the same function to generate the legend, like so (at the end of your script)

var legendHTML = '';
barData.labels.forEach(function(label, i) {
    legendHTML += ('<li><span style="background: ' + getFillColor(i) + '"></span>' + label + '</li>');
})
document.getElementById("totalPopulationByPurokLegend").innerHTML = '<ul class="chartLegend">' + legendHTML + '</ul>';

with CSS

.chartLegend {
    list-style: none;
    margin: 0;
    font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
    font-size: 12px;
    font-color: #666;
}

.chartLegend span {
    display: inline-block;
    height: 10px;
    width: 10px;
    margin-right: 10px;
}

You don’t need the legendTemplate option by the way.

Leave a comment