I want to add a button that allows users to toggle all the series on/off in one click, i.e., a button that simulates a click on all the legend labels.
How can I accomplish this?
@nishantroy what you should do is:
function handleClick() {
chartInstance.data.datasets.forEach(function(ds) {
ds.hidden = !ds.hidden;
});
chartInstance.update();
}
This works, but now when I manually click one or two labels and then try toggling again, it toggles everything except the two I manually clicked.
Also, this doesn't work for pie charts.
To get manually toggled series to work as well:
ds.hidden = !ds.hidden
ds._meta[0].hidden = !ds._meta[0].hidden
ds._meta[0].dataset.hidden = !ds._meta[0].dataset.hidden
To get manually toggled series to work as well:
ds.hidden = !ds.hidden ds._meta[0].hidden = !ds._meta[0].hidden ds._meta[0].dataset.hidden = !ds._meta[0].dataset.hidden
@jameshiew thank you for your answer, 2 years later it saved me a lot of time.
However I am not sure to understand the logic here, do you think you could explain these 2 lines?
Also, the issue is after that, 2 clicks instead of 1 are required to update the chart by clicking on the legend... How should I fix that?
Thank you!
@zenlouis sorry I can't be of much help, I don't think I've touched chart.js since then so don't really remember what I was doing. It looks like the project has a Slack so could be worth asking there - https://chartjs-slack.herokuapp.com/
This is still not working, once I check a legend label it doesn't change visibility anymore
@etimberg
Its working fine but the issue is once I click on show/hide button, then individual lables works only after double click instead of single click for first time. Can you please help me out how can I fix this issue. I want labels to work for first click instead of double click.
If anyone is still struggling with the issue of needing 2 clicks, I had to make it work by then overriding the legend on click behavior. I'm using a react wrapper over chart.js, hence the chartRef, but that's basically just the chart instance:
legend: {
onClick: (e, legendItem) => {
const ci = chartRef.current?.chartInstance;
const i = legendItem.datasetIndex;
if (ci && ci.data.datasets && i !== undefined) {
let meta = ci.getDatasetMeta(i);
meta.hidden =
meta.hidden === undefined
? !ci.data.datasets[i].hidden
: !meta.hidden;
ci.update();
}
},
},