Use the listeners option to register callbacks that trigger when a label event is detected. The listeners object uses event names as keys and callback functions as values.
Callback Arguments
Each callback receives two arguments:
context: An object containing label information (similar to scriptable options). You can modify this object to store state.event: The Chart.js event object (e.g., containing x, y, and native properties).
Triggering Re-renders
If a listener callback explicitly returns true, the context is updated with any modifications you made, and the chart is re-rendered. This is the standard way to implement visual interactions like highlighting or selection.
Configuration Scope
Listeners can be scoped in two ways:
- Global (Plugin-wide): Registered under
options.plugins.datalabels.listeners. These apply to all labels in the chart. - Dataset-specific: Registered under
dataset.datalabels.listeners. These apply only to labels within that specific dataset.
Note: If no listeners are registered, incoming events are ignored, ensuring no performance penalty for charts that do not use interactivity.
// Example of a dataset-specific listener
{
datasets: [{
datalabels: {
listeners: {
click: function(context, event) {
console.log('Clicked label index:', context.dataIndex);
}
}
}
}]
}