Chartjs-Why this Tooltip callback for ChartJS works and this doesn't

1👍

your first snippet will also work

tooltips: {
    callbacks: {
        labelColor : function(tooltipItem, chartInstance){
            return {
                    backgroundColor : data.datasets[tooltipItem.datasetIndex].backgroundColor,
                    borderColor : data.datasets[tooltipItem.datasetIndex].backgroundColor
            };
        }
    }
}

here your callback function for labelColor has two arguments. second argument chartInstance contains data and other properties you need but your are trying to access data.datasets instead of chartInstance.data.datasets.

check out this example snippet.

var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
  // The type of chart we want to create
  type: 'line',

  // The data for our dataset
  data: {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    datasets: [{
      label: 'My First dataset',
      backgroundColor: 'rgb(255, 99, 132)',
      borderColor: 'rgb(255, 99, 132)',
      data: [0, 10, 5, 2, 20, 30, 45]
    }]
  },

  // Configuration options go here
  options: {
    tooltips: {
      callbacks: {
        labelColor: function(tooltipItem, chartInstance) {
          debugger;
          return {
            backgroundColor: chartInstance.data.datasets[tooltipItem.datasetIndex].backgroundColor,
            borderColor: chartInstance.data.datasets[tooltipItem.datasetIndex].backgroundColor
          };
        },


        label: function(tooltipItem, data) {
          var label = data.datasets[tooltipItem.datasetIndex].label || '';

          if (label) {
            label += ': ';
          }
          label += Math.round(tooltipItem.yLabel * 100) / 100;
          label += ' custom'
          return label;
        }
      }
    }

  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart"></canvas>

Leave a comment