Reputation: 165
I am developing a web application using chart.js library. I am trying to add a custom filter for charts when the user clicks on legend's checkboxes. However I don't know how to configure chart.js to call my custom filter.
For example here are the charts of my application
Then I click on Temperature's checkbox and Temperature chart is hidden
When I cliked on Temperature's checkbox, Chart.js called his default on click function to filter the charts.
I have defined my own filter function :
public newLegendClickHandler(e, legendItem) {
let index = legendItem.datasetIndex;
let ci = this.chart;
[ci.getDatasetMeta(0),
ci.getDatasetMeta(1),
ci.getDatasetMeta(2)].forEach(function (meta) {
meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
});
ci.update();
}
When I click on a checkbox I would like to call this function and not Chart.js default filter function.
I have already read chart.js documentation "Custom On Click Actions" and, I don't understand why the legend attribute is empty in the example given by Chart.js team.
If you know how to replace default onclick function for legend items, I will be glad to know the solution :)
Thank you in advance.
Upvotes: 1
Views: 7488
Reputation: 32879
You can use the native onClick
event handler method of the legend.
So.. in your chart options, define the following :
options: {
legend: {
onClick: newLegendClickHandler
},
...
}
this will override the default on-click event handler function of the legend.
ᴅᴇᴍᴏ
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar'],
datasets: [{
label: 'LINE',
data: [3, 1, 4],
backgroundColor: 'rgba(0, 119, 290, 0.2)',
borderColor: 'rgba(0, 119, 290, 0.6)'
}]
},
options: {
legend: {
onClick: newLegendClickHandler
}
}
});
function newLegendClickHandler() {
alert('newLegendClickHandler function has been called!');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>
Upvotes: 2