[Chartjs]-ChartJS v2 custom tooltip for rLabel

7👍

The rLabel value is not a property of tooltipItem that’s why it gives undefined. I access that value from the data object.

  tooltips: {
                callbacks: {
                    label: function(tooltipItem, data) {
                        rLabel = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].r;
                        var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || '';
                        return datasetLabel + ' : ' + rLabel + '% har pris på ca. ' + tooltipItem.yLabel + ' kr.';
                    }
                }
            }

Below is the working code for the same.

var data = {
        datasets: [
            {
                label: 'First Dataset',
                data: [
                    {
                        x: 20,
                        y: 30,
                        r: 15
                    },
                    {
                        x: 40,
                        y: 10,
                        r: 10
                    }
                ],
                backgroundColor:"#FF6384",
                hoverBackgroundColor: "#FF6384",
            }
        ]
    };
    var myBubbleChart = new Chart(ctx,{
        type: 'bubble',
        data: data,
        options: {
            tooltips: {
                callbacks: {
                    label: function(tooltipItem, data) {
                        rLabel = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].r;
                        var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || '';
                        return datasetLabel + ' : ' + rLabel + '% har pris på ca. ' + tooltipItem.yLabel + ' kr.';
                    }
                }
            }
        }
    });

1👍

After trying for hours, turns out in my case, I needed to add var before rLabel

Otherwise, it just kept alerting me there was a js error in developer console…

In my case :

tooltips: {
  callbacks: {
    label: function(tooltipItem, data) {
      var rLabel = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].r;
      var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || '';
      return datasetLabel + ' : ' + rLabel + '% har pris på ca. ' + tooltipItem.yLabel + ' kr.';
    }
  }
}

Still, thanks very very much for the answer from Sanjay Dutt !

0👍

this may help in solving the build error.

 label: function(tooltipItem, data) {
        let radiusArr:any;
        radiusArr = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
        let rLabel = radiusArr.r;
        let datasetLabel = data.datasets[tooltipItem.datasetIndex].label || '';
        return rLabel + ' xxx are ' + datasetLabel;
    },

Leave a comment