Scriptable properties

Tooltips have three properties that receive functions. One allows you to replace the Canvas-generated tooltips with your own custom HTML tooltips. The other two allow sorting of tooltip items (when several items appear in a single tooltip) and filtering. These properties are listed as follows:

Object

Parameters

Description

custom

(tooltipModel)

Used to generate custom HTML tooltips. See the Custom HTML tooltips section on HTML tooltips in this chapter.

filter

(item, data); array of datasets in data.datasets; array of labels in data.labels; item.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, and item.datasetIndex is the index of its dataset.

A function that returns true or false and is called before rendering a tooltip item. If it returns false, the item will not be rendered.

itemSort

(item1, item2); each parameter is an item object with the following properties: x, y, xLabel, yLabel, index, dataSetIndex.

Sorts items (in tooltips that contain multiple items). The function returns a number. If item1 < item2 the function should return negative value, if item1 > item2 a positive value should be returned, and zero should be returned if they are equal.

Scriptable properties for tooltips

Let’s see some examples. In the following code (Tooltip/tooltip-4-script-filter.html), the filtering function ignores all items that contain y values greater than 20. Additionally, the events key was used to reduce the events the tooltips respond to. In this example, they are only activated with clicks:

const data = {
labels: ["One", "Two", "Three", "Four"],
datasets: [{label:'Dataset 1',… },{label:'Dataset 2',…},
{label:'Dataset 3',…}]
};
new Chart('chart', { type: 'line', data: data,
options: {
legend: { display: false },
tooltips: {
mode: 'index',
intersect: false,
filter: (item, data) => data.datasets[item.datasetIndex]
.data[item.index] < 20
},
events: ['click']
}
});

The following screenshot shows the result of clicking near the values points of index 1. Since one of the three points is greater than 20, it doesn't show up in the tooltip:

Tooltip with mode: index filtering only items that have a y value less than 20. Code: Tooltip/tooltip-4-script-filter.html.

This other example (Tooltip/tooltip-5-script-sort.html) configures item sorting in ascending order by the y value, in the same chart:

new Chart('chart', { type: 'line', data: data,
options: {
legend: { display: false },
tooltips: {
mode: 'index',
intersect: false,
itemSort: (a,b) => b.y - a.y
},
events: ['click']
}
});

The result is as follows. Note that the tooltip items are ordered by their y value:

Tooltip with mode: ‘index’ sorting items by their y value. Code: Tooltip/tooltip-5-script-sort.html.
..................Content has been hidden....................

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