3

In Chart.js v2, the datasetIndex property of ChartTooltipItem[] identifies which segment of a stacked bar chart was clicked. This allowed the tooltip content to be customized for each segment of the stacked bar chart.

In v3, TooltipItem[] provides the datasets but does not identify which one was clicked. There is a datasetIndex field for each TooltipItem, but it just matches the index in TooltipItem[] rather than identify the clicked segment.

Has anyone found a field in the V3 tooltip callback to identified which segment of a stacked bar chart was clicked? Or was this functionality lost in the v3 rewrite?

1 Answers1

2

It just works fine, the only thing that is different is that it seems like in v2 it defaulted to the point mode while now it is using index mode, if you change it back to point it works as expected:

var options = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        backgroundColor: 'red'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        backgroundColor: 'blue'
      }
    ]
  },
  options: {
    plugins: {
      tooltip: {
        mode: 'point',
        callbacks: {
          beforeBody: (ttItems, x) => {
            ttItems.forEach((ttItem) => {
              console.log('BeforeBody: ', ttItem.datasetIndex, ttItem.dataIndex)
            })
          },
          afterBody: (ttItems, x) => {
            ttItems.forEach((ttItem) => {
              console.log('AfterBody: ', ttItem.datasetIndex, ttItem.dataIndex)
            })
          }
        }
      }
    },
    scales: {
      y: {
        stacked: true
      },
      x: {
        stacked: true
      }
    }
  }
}

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.4.1/chart.js"></script>
</body>
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69