Chart.js legend callbacks: unresolved dataset visibility toggle timing
0 reputation · 13 Jul 2023, 20:18 UTC
0 reputation · 13 Jul 2023, 20:18 UTC
Determine how the Chart.js legend onClick handler updates the dataset.hidden flag relative to a custom onClick callback across major releases.
Chart.js 2.x updates the flag before the callback, while 3.x and 4.x update it after. The library documentation lists the callback signature but omits the order of operations, leaving developers uncertain when to read the flag within custom callbacks.
Because the toggle order affects the state seen by custom legend logic, it can lead to bugs when multiple datasets are programmatically toggled or when the callback modifies visibility. No official hook exists to expose the sequence, and future releases may change it.
dataset.hidden update after the onClick callback or before?dataset.hidden?34275 reputation · 13 Jul 2023, 21:01 UTC
dataset.hidden flag updates AFTER the onClick callback.The behavior of the legend visibility toggle has changed significantly between version 2.x and the 3.x/4.x releases. This shift determines whether your custom onClick logic sees the state of the dataset before or after the user interaction has been processed.
dataset.hidden flag before executing the custom onClick callback. Consequently, if you read the flag inside the callback, you are seeing the "post-toggle" state.onClick callback before updating the dataset.hidden flag. Reading the flag within the callback provides the "pre-toggle" state (the state as it existed before the click).Because of this shift, custom legend logic should be designed based on the specific goal of the state check:
dataset.hidden. If it is false, the user is attempting to hide it.Chart.js does not currently provide a dedicated hook like beforeVisibilityToggle or afterVisibilityToggle for legend legend. The order of operations is handled within the internal legend-item interaction methods. While there is no official indication of a change in future minor releases, developers should encapsulate visibility logic in helper functions to guard against potential breaking API shifts.
To verify this in your environment, you can use the following snippet:
options: {
legend: {
onClick: (event, legendItem, chart) => {
const dataset = chart.data.datasets[legendItem.index];
console.log('State during callback:', dataset.hidden);
// In v4.x, this is the PRE-toggle state
// Call default behavior if you want the toggle to still happen
// Chart.defaults.legend.onClick(event, legendItem, chart);
}
}
}
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.