Tooltip callbacks

With callbacks, you can dynamically generate the text contents and colors of the items displayed in a tooltip based on data values and other accessible attributes. The Callbacks are properties of the tooltips.callbacks object, which can be configured globally (Chart.defaults.global.tooltips.callbacks) or locally per chart instance (options.tooltips.callbacks). They are listed in the table as follows:

Object

Parameters

Description

beforeTitle, title, afterTitle

(item[], data); array of datasets in data.datasets; array of labels in data.labels; each item element contains the following properties: x, y, xLabel, yLabel, index, dataSetIndex.

The title function returns the text for the tooltip title. You can also implement other functions to include text above or below it.

beforeBody, body, afterBody

The body function returns the text for the tooltip body (including labels). You can also implement other functions to include text above or below it.

beforeFooter, footer, afterFooter

The footer function returns the text for the tooltip footer. You can also implement other functions to include text before or after it.

beforeLabel, label, afterLabel

(item,data); array of datasets in data.datasets; array of labels in data.labelsitem.x and item.y contain coordinates of the value point, item.xLabel and item.yLabel the labels in each axis, item.index is the index of the item in the dataset, item.datasetIndex is the index of its dataset.

The label function returns the text for this label. You can also implement other functions to include text above or below one or more labels.

labelColor

(item, chart)

The function returns the color of the text box of an individual item label

labelTextColor

(item, chart)

The function returns the color of the text for an individual item label

Callbacks to create and change the text contents of tooltips

The following example (Tooltips/tooltip-6-callback.html) uses callbacks to add extra text to the title, insert separator characters above and below the item labels, and append a footer containing the average of all the value points:

new Chart('chart', { type: 'horizontalBar', data: data,
options: {
legend: { display: false },
tooltips: {
mode: 'index',
callbacks: {
footer: (items, data) => 'Average: ' + (data.datasets
.map(d=>d.data[items[0].index])
.reduce((a,b)=>a+b, 0) /
items.length)
.toFixed(2),
title: (items, data) => "Stage " + items[0].yLabel,
beforeBody: () => '============',
afterBody: () => '------------------',
}
},
events: ['click']
}
});

The result is as follows:

Tooltip with a footer, extra text in title, and separators before and after body created with callbacks. Code: Tooltips/tooltip-6-callback.html.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset