[Chartjs]-How to disable chartjs legendclick

78👍

According to the docs there is a onClick handler for the legend exposing the event object. If you stopPropagation it stops the data series hiding:

        let chart = new Chart(elem.find('canvas')[0], {
                type: 'line',
                data: {
                    labels: [],
                    datasets: []
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    legend: {
                        onClick: (e) => e.stopPropagation()
                    }
                }
            });

The above is ES6, if your not using a supported browser below is the older ES5 equivilant.

legend: {
    onClick: function (e) {
        e.stopPropagation();
    }
}

Chartjs must register its own click event after the legend.onClick which is why this stop it executing.

docs

20👍

Also, you can use null or any value which is evaluated false to disable click event on all legend.

options: {
    legend: {
        onClick: null
    }
}

Note: Ignore click event by onClick on following code in Chart.js ( https://github.com/chartjs/Chart.js/blob/6bea15e7cf89003e3a5945a20cf1d2cc5096728e/src/plugins/plugin.legend.js#L481 )

16👍

At the time of writing (Chart.js v3.5.1), the correct answer is

options: {
  plugins: {
    legend: {
      onClick: null
    }  
  }
}

As per Natan Almeida de Lima’s comment above. Adding it as an answer since I didn’t see it as a one-line comment which I only found after figuring it out for myself.

7👍

To override the default behavior of clicking on a legend item, that is showing/hiding the associated dataset in the chart, you may use the following option (shown inside options for clarity):

options: {
    legend: {
        onClick: function(event, legendItem) {}
    }
}

This is the way to override the default behavior, that is by supplying a function with the same arguments. According to your requirements, this function should have an empty body (and, thus, return immediately), since absolutely nothing should happen when clicking on a legend item. Look for legend.onClick in the docs. While it currently appears under only two chart types, this option should work for all chart types.

-1👍

You need to add properties legendItemClick to override default action. It’s work good for pie chart

legendItemClick: function(e){
                    console.log("Clicked an item with text: " + e.text);
                    e.preventDefault();
                }

https://docs.telerik.com/kendo-ui/api/javascript/dataviz/ui/chart/events/legenditemclick

Leave a comment