[Chartjs]-How to trigger ChartJS legend onClick with out interrupting its normal working

2👍

It almost seems like that the example of the documentation is wrong, seems like they dont give the chart which is why it fails, if you provide the chart yourself and write the full onclick it does work

Example:

const defaultLegendClickHandler = Chart.defaults.global.legend.onClick;
var newLegendClickHandler = function(e, legendItem) {
  alert(legendItem.text)
  const index = legendItem.index;


  const {
    type
  } = chart.config;
  if (type === 'pie' || type === 'doughnut') {
    // Pie and doughnut charts only have a single dataset and visibility is per item
    for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
      meta = chart.getDatasetMeta(i);
      // toggle visibility of index if exists
      if (meta.data[index]) {
        meta.data[index].hidden = !meta.data[index].hidden;
      }
    }
  } else {
    const index = legendItem.datasetIndex;
    const ci = this.chart;
    const meta = ci.getDatasetMeta(index);

    // See controller.isDatasetVisible comment
    meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;

    // We hid a dataset ... rerender the chart
    ci.update();
  }
  chart.update();

};

const options = {
  type: 'pie',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderWidth: 1
    }, {
      label: '# of Votes2',
      data: [12, 19, 3, 5, 2, 3],
      borderWidth: 1
    }, {
      label: '# of Votes3',
      data: [12, 19, 3, 5, 2, 3],
      borderWidth: 1
    }, {
      label: '# of Votes4',
      data: [12, 19, 3, 5, 2, 3],
      borderWidth: 1
    }]
  },
  options: {
    legend: {
      onClick: newLegendClickHandler
    }

  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>

Leave a comment