Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 749
Preethy Avatar asked Jul 26 '16 07:07

Preethy


People also ask

How do you turn off legend in Chartjs?

To remove legend on charts with Chart. js v2 and JavaScript, we can set the options. legend to false . const chart1 = new Chart(canvas, { type: "pie", data: data, options: { legend: { display: false, }, tooltips: { enabled: false, }, }, });

How do I remove a legend from a chart?

Tip: To quickly remove a legend or a legend entry from a chart, you can select it, and then press DELETE. You can also right-click the legend or a legend entry, and then click Delete.

How do I hide the legend in a line graph?

According to the official documentation (https://www.chartjs.org/docs/latest/configuration/legend.html), to hide the legend, the display property of the options. display object must be set to false .

What is a legend in chart js?

The chart legend displays data about the datasets that are appearing on the chart.


4 Answers

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

like image 169
ste2425 Avatar answered Oct 21 '22 17:10

ste2425


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 )

like image 23
Sheile Avatar answered Oct 21 '22 16:10

Sheile


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.

like image 13
Q---ten Avatar answered Oct 21 '22 16:10

Q---ten


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.

like image 7
xnakos Avatar answered Oct 21 '22 17:10

xnakos