Chartjs-ChartJS 3.7.1 tooltip callback, get label value for the next index

0👍

You get access to the chart object and have the data index so you can just get the correct label from the labels array like so:

title: (items) => {
  const item = items[0];
  const {
    chart
  } = item;
  const nextLabel = chart.data.labels[item.dataIndex + 1] || '';
  return `${item.label}, next label: ${nextLabel}`;
}
const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'orange'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'pink'
      }
    ]
  },
  options: {
    plugins: {
      tooltip: {
        callbacks: {
          title: (items) => {
            const item = items[0];
            const {
              chart
            } = item;
            const nextLabel = chart.data.labels[item.dataIndex + 1] || '';
            return `${item.label}, next label: ${nextLabel}`;
          }
        }
      }
    }
  }
}

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

Leave a comment