Chart.JS custom legend onClick event returns error when calling original event handler

2πŸ‘

βœ…

It seems to work fine, although the rest of your config is slightly wrong, the scales and title object dont belong in the legend object and the scales are no arrays anymore.

Working example of default click:

// dummy array and methods so no errors
const consumption = [];
const recalculateConsumptionSum = () => {};
const restoreConsumptionItem = (e) => {};

var options = {
  type: 'pie',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1,
        backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1,
        backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
      }
    ]
  },
  options: {
    scales: {
      /* x: {  comment scale config out because we dont want the x axis lines behind our douhgnut
        ticks: {
          display: false
        }
      } */
    },
    plugins: {
      legend: {
        onClick: (e, legendItem, legend) => {
          /**
           * Stores original event handler for legend onClick 
           * and executes it so we don't override it.
           */
          if (legend.chart.config.type === 'pie' || legend.chart.config.type === 'doughnut') {
            Chart.controllers.doughnut.overrides.plugins.legend.onClick(e, legendItem, legend)
          } else {
            Chart.defaults.plugins.legend.onClick(e, legendItem, legend);
          }

          /**
           * Custom legend item handler
           */
          let toBeRemoved = consumption.find((c) => c.categoryName === legendItem.text);
          let toBeRemovedIndex = consumption.indexOf(toBeRemoved);

          if (toBeRemoved) {
            // Hide consumption item from table
            this.hideConsumptionItem(toBeRemoved, toBeRemovedIndex);
            // Recalculate consumption sum
            this.recalculateConsumptionSum();
          } else {
            // Restore hidden item from saved items
            restoreConsumptionItem(legendItem);
            // Recalculate consumption sum
            recalculateConsumptionSum();
          }
        },
        labels: {
          color: '#4f4f51',
          padding: 10,
          boxWidth: 40,
          font: {
            size: 12
          }
        },
      },
      title: {
        display: false
      }
    }
  }
}

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.3.2/chart.js"></script>
</body>

Leave a comment