Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I’m currently migrating from 2.9.3 to 3.7.1 and I’m having trouble with migrating a callback function from the options object.

Former location: options.tooltips.callbacks.title
Migrated location: options.plugins.tooltip.callbacks.title

Former function (simplified):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function (tooltipItems, data) {
    var tooltipItem = tooltipItems[0];
    var currentLabel = data.labels[tooltipItem.index];
    var nextLabel = data.labels[tooltipItem.index +1];
    return currentLabel + ' - ' + nextLabel;
}

Migrated function:

function (tooltipItems) {
    var tooltipItem = tooltipItems[0];
    var currentLabel = tooltipItem.label;
    var nextLabel = ? // how to get nextLabel?
    return currentLabel + ' - ' + nextLabel;
}

tooltipItem.dataset has a label array but that appears empty when i console.log(tooltipItems)

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading