How to add an event to chart.js legend?

by edmond_brakus , in category: Javascript , 10 months ago

How to add an event to chart.js legend?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 10 months ago

@edmond_brakus 

To add an event to the Legend of a Chart.js chart, you can use the onClick callback function in the options of the chart.


Here is an example of how to add an event to the legend:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
var chartOptions = {
    legend: {
        onClick: function(event, legendItem) {
            // Your event code here
            console.log('Clicked on legend item: ', legendItem);
        }
    },
    // Additional chart options...
};

var myChart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: chartOptions
});


In the above code, the onClick function is added to the legend object in the chartOptions. When a legend item is clicked, the function will be called with the event and legendItem parameters. You can add your custom event code within this function, such as logging the clicked legend item.


Remember to replace ctx with the variable representing your chart's context and data with your actual chart data.


This event can be useful for performing actions based on legend item clicks, such as filtering or interacting with other elements of the chart.