Preethy
Preethy

Reputation: 722

How to disable chartjs legendclick

I would like to disable chart.js Spider chart legend click because when I click on the legend the data series is hiding the associated set of values as shown in the below images.

enter image description here

enter image description here

My requirement is that I do not want to disable the dataset. I have tried the preventDefault(); on the chart click but it is not working.

My code sample is attached below. Please check..

<!doctype html>
<html>

<head>
    <title>Radar Chart</title>
    <script src="../dist/Chart.bundle.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

<body>
    <div style="width:75%">
        <canvas id="canvas"></canvas>
    </div>
    <script>
    var randomScalingFactor = function() {
        return Math.round(Math.random() * 100);
    };
    var randomColorFactor = function() {
        return Math.round(Math.random() * 255);
    };
    var randomColor = function(opacity) {
        return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')';
    };

    var config = {
        type: 'radar',
        data: {
            labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"],
            datasets: [{
                label: "My First dataset",
                backgroundColor: "rgba(0,0,0,0.5)",
                pointBackgroundColor: "rgba(220,220,220,1)",
                data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
            },  {
                label: "My Second dataset",
                backgroundColor: "rgba(0,120,0,0.5)",
                pointBackgroundColor: "rgba(151,187,205,1)",
                hoverPointBackgroundColor: "#fff",
                pointHighlightStroke: "rgba(151,187,205,1)",
                data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
            },]
        },
        options: {
            legend: {
                position: 'top',
                onClick: (e) => e.stopPropagation()
            },
            title: {
                display: true,
                text: ''
            },
            scale: {
              reverse: false,
              gridLines: {
                color: ['black']
              },
              ticks: {
                beginAtZero: true
              }
            }
        }
    };

    window.onload = function() {
        window.myRadar = new Chart(document.getElementById("canvas"), config);
    };





    </script>
</body>

</html>

Upvotes: 31

Views: 43280

Answers (6)

Tommy
Tommy

Reputation: 2453

For Chart.js version 4.4.0, you can use the following solution:

options: {
  plugins: {
    legend: {
      onClick: (e) => e.native.stopPropagation()
    }  
  }
}

Additional information: The Event triggered by onClick (in the example: e) has the following type: ChartEvent.

Upvotes: 0

Q---ten
Q---ten

Reputation: 2536

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.

Upvotes: 24

user11696468
user11696468

Reputation: 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

Upvotes: -1

ste2425
ste2425

Reputation: 4806

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

Upvotes: 79

Sheile
Sheile

Reputation: 443

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 )

Upvotes: 21

xnakos
xnakos

Reputation: 10196

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.

Upvotes: 7

Related Questions