[Chartjs]-Chartjs legend onclick doesn't strikethrough

2👍

This is because you never set the hidden property in your generateLabels so chart.js does not know which labels to strikethrough since they are never hidden for the legend plugin.

const autocolors = window['chartjs-plugin-autocolors'];

Chart.register(autocolors);

var options = {
  type: 'line',
  data: {
    labels: ["0", "1", "2", "3", "4", "5"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3]
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7]
      },
      {
        label: '# of People',
        data: [3, 1, 15, 4, 9, 12]
      }
    ]
  },
  options: {
    plugins: {
      autocolors: {
        mode: 'dataset'
      },

      legend: {
        onClick: (evt, legendItem, legend) => {
          //console.log(legendItem);
          const index = legendItem.datasetIndex;
          const ci = legend.chart;

          legend.chart.data.datasets.forEach((d, i) => {
            ci.hide(i);
            d.hidden = true;
          })

          ci.show(index);
          legendItem.hidden = false;

          ci.update();
        },
        labels: {
          generateLabels: (chart) => {
            const datasets = chart.data.datasets;

            legends = [];
            for (let i = 0; i < datasets.length; i++) {
              const meta = chart.getDatasetMeta(i)
              let total = datasets[i].data.reduce((total, item) => total + item);
              legends.push({
                text: `${datasets[i].label} (${total.toLocaleString()})`,
                fillStyle: datasets[i].borderColor,
                datasetIndex: i,
                strokeStyle: 'red',
                hidden: !meta.visible
              });
            }

            return legends;
          }
        }
      }
    }
  }
}

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.9.1/chart.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-autocolors"></script>
</body>

Leave a comment