Chartjs-Getting clicked object from each section of a single stack bar as my stack bar has multiple sections Chart.js

1👍

You can define the showData function as follow, this will also if your datasets contain more than one value:

function showData(evt) {
  const datasetIndex = chart.getElementAtEvent(event)[0]._datasetIndex;
  const index = chart.getElementAtEvent(event)[0]._index;
  const model = chart.getElementsAtEvent(event)[datasetIndex]._model;
  console.log(model.datasetLabel, chart.config.data.datasets[datasetIndex].data[index]);
}

Instead of adding the (click) event handler directly on the canvas, I would also rather define the onClick function within the chart options as follows:

options: {
  onClick: showData,

Please have a look at the runnable code snippet.

function showData(evt) {
  const datasetIndex = chart.getElementAtEvent(event)[0]._datasetIndex;
  const index = chart.getElementAtEvent(event)[0]._index;
  const model = chart.getElementsAtEvent(event)[datasetIndex]._model;
  console.log(model.datasetLabel, chart.config.data.datasets[datasetIndex].data[index]);
}

const chart = new Chart("Chart1", {
  type: 'bar',
  data: {
    labels: ['A', 'B'],
    datasets: [{
        label: 'Data1',
        data: [27, 22],
        backgroundColor: 'red'
      },
      {
        label: 'Data2',
        data: [40, 15],
        backgroundColor: 'orange'
      },
      {
        label: 'Data3',
        data: [12, 31],
        backgroundColor: 'blue'
      }
    ]
  },
  options: {
    onClick: showData,
    legend: {
      display: false
    },
    tooltips: {
      enabled: false
    },
    responsive: true,
    scales: {
      xAxes: [{
        stacked: true,
      }],
      yAxes: [{
        stacked: true,
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
canvas {
  max-width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="Chart1" height="200"></canvas>

Leave a comment