HTML legend example

Hello, I love this plugin to be able to create charts. However, I’ve looked and cannot understand or find a way to use the legendCallback function to create an HTML legend.

Can you provide a link or an example of how to use the legendCallback or chartInstance.generateLegend? I have read the documentation and scoured the issues, but am not familiar on how to customize this code. What does the HTML legend look like?

Author: Fantashit

1 thought on “HTML legend example

  1. @sensaetions The default generateLegend() function will generate a <ul class="0-legend"> for the chart, which you can style using the css descriptor [class="0-legend"]. The 0 is the
    In the following example you’ll find a chart with a HTML generated legend, which mimics the default legend.


    [class="0-legend"] {
      list-style: none;
      cursor: pointer;
      padding-left: 0;
    [class="0-legend"] li {
      display: inline-block;
      padding: 0 5px;
    [class="0-legend"] li.hidden {
      text-decoration: line-through;
    [class="0-legend"] li span {
      border-radius: 5px;
      display: inline-block;
      height: 10px;
      margin-right: 10px;
      width: 10px;

    JavaScript to create HTML legend

    var myLegendContainer = document.getElementById("myChartLegend");
    // generate HTML legend
    myLegendContainer.innerHTML = myChart.generateLegend();
    // bind onClick event to all LI-tags of the legend
    var legendItems = myLegendContainer.getElementsByTagName('li');
    for (var i = 0; i < legendItems.length; i += 1) {
      legendItems[i].addEventListener("click", legendClickCallback, false);

    JavaScript legend onClick callback

    function legendClickCallback(event) {
      event = event || window.event;
      var target = || event.srcElement;
      while (target.nodeName !== 'LI') {
          target = target.parentElement;
      var parent = target.parentElement;
      var chartId = parseInt(parent.classList[0].split("-")[0], 10);
      var chart = Chart.instances[chartId];
      var index =;
 , event, chart.legend.legendItems[index]);
      if (chart.isDatasetVisible(index)) {
      } else {

    default legendCallback

    legendCallback: function(chart) {
    var text = [];
    text.push(‘<ul class=”‘ + + ‘-legend”>’);
    for (var i = 0; i <; i++) {
    text.push(‘<li><span style=”background-color:’ +[i].backgroundColor + ‘”></span>’);
    if ([i].label) {
    return text.join();

    Edit: modified legendClickCallback to call the chart onClick-event.

Comments are closed.