jelhan
jelhan

Reputation: 6338

ChartJS: Update tooltip

I'm having a chart build with ChartJS. I'm including datasets.label in multipleTooltipLabel template and facing an update issue. When changing a datasets.label and running chart.update() the tooltip is not updated. I created a JSFiddle demonstrating the issue.

The code I use to include datasets label in tooltip:

var options = {
  multiTooltipTemplate: "<%=datasetLabel%>: <%= value + ' %' %>"
};

Beside that option I followed ChartJS usage example for Line charts.

Change label and update chart:

myNewChart.datasets[0].label = 'updated label';
myNewChart.update();

Label shown in tooltip is not updated...

I had a look in ChartJS source code and figured out that showTooltip function is called with a ChartElements array which was not updated.

Update: I might cached the issue. label of dataset is set on each point element and not updated if it changes. showTooltip used this "cached" dataset label when drawing a tooltip. Perhaps this should not be a question on StackOverflow but a bug report for ChartJS.

Upvotes: 1

Views: 4416

Answers (3)

Eyni Kave
Eyni Kave

Reputation: 1530

var option = {
    plugins: {
        tooltip: {
            callbacks: {
                label: function (context) {
                    //console.log(context);
                    label = 'new string ' + context.label + ', ' + context.dataIndex;
                    return label;
                }
            }
        }
    }
};

myChart.options = option;

ToolTips / Points Events are configurable with chartJS options...

enter image description here

Find more here: https://www.chartjs.org/docs/latest/configuration/tooltip.html

Upvotes: 0

jelhan
jelhan

Reputation: 6338

I found a solution:

myNewChart.datasets[0].points.forEach(function(point) {
  point.datasetLabel = 'updated label';
});

This might also be the way it should be done. Chart.js documentation of update method says you should set myLineChart.datasets[0].points[2].value = 50; to change the value. That's confusing cause on creation dataset expects the values in data property. points is generated by Chart.Line Class on init. Naming may be different for other chart types (eg. it's bars for a bar chart).

I'm not quite sure if myLineChart.datasets[0].label value is used somewhere or if could be unchanged.

Upvotes: 1

Siderite Zackwehdex
Siderite Zackwehdex

Reputation: 6570

I could solve your problem by changing the original data object (data.datasets[0].label='updated label') then running myNewChart.initialize(data).

Upvotes: 0

Related Questions