Custom Legend with ChartJS v2.0

If you guys run through this post and tried the posted answer and didn’t work,
try this one:

  legendCallback: function(chart) {
    var text = [];
    text.push('<ul>');
    for (var i=0; i<chart.data.datasets.length; i++) {
      console.log(chart.data.datasets[i]); // see what's inside the obj.
      text.push('<li>');
      text.push('<span style="background-color:' + chart.data.datasets[i].borderColor + '">' + chart.data.datasets[i].label + '</span>');
      text.push('</li>');
    }
    text.push('</ul>');
    return text.join("");
  },

Then add this below:

document.getElementById('chart-legends').innerHTML = myChart.generateLegend();

To create the legends. Make sure you have an element <div id="chart-legends"></div>

Leave a Comment