[Chartjs]-How to get click event in Chart.js

12👍

below code is for bar chart Add Data keys in orders of Labels in my case it was theChart in your case it is myChart

datakeys: ["4", "3", "2", "1", "6"],

 document.getElementById("chart_VulSev").onclick = function (evt) {
                    var activePoints = theChart.getElementAtEvent(evt);
                    var theElement = theChart.config.data.datasets[activePoints[0]._datasetIndex].data[activePoints[0]._index];
                    //console.log(activePoints);
                    //console.log(theElement);
                    //console.log(theChart.config.data.datakeys[activePoints[0]._index]);
                    window.open("page.aspx?id=" + theChart.config.data.datakeys[activePoints[0]._index]);
                    //alert(theChart.config.data.datakeys[activePoints[0]._index]);
                    //console.log(theChart.config.type);
                }

For Pie Chart check this snippet

<html>

<head>
  <title>PieChart</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script>

  <script>
    var data = {
      datasets: [{
        data: [300, 50, 100, 200],
        backgroundColor: [
          "#a02020",
          "#ed1c24",
          "#ff9900",
          "#109618",
        ]
      }],
      labels: [
        "Critical",
        "High",
        "Medium",
        "Low"
      ]
    };

    $(document).ready(
      function() {
        var canvas = document.getElementById("myChart");
        var ctx = canvas.getContext("2d");
        var myNewChart = new Chart(ctx, {
          type: 'pie',
          data: data
        });

        canvas.onclick = function(evt) {
          var activePoints = myNewChart.getElementsAtEvent(evt);
          var chartData = activePoints[0]['_chart'].config.data;
          var idx = activePoints[0]['_index'];

          var label = chartData.labels[idx];
          var value = chartData.datasets[0].data[idx];

          var url = "http://example.com/?label=" + label + "&value=" + value;
          console.log(url);
          alert(url);
        };
      }
    );
  </script>

</head>

<body>
  <div style="width: 320.750px; height: 156px">
    <canvas id="myChart"></canvas>
  </div>
</body>

</html>

8👍

The docs are not very clear, but the new way of handling it is like this:

var myChart = new Chart(ctx, {

    ...

    options: {
        onClick: (evt, item) => {
            let index = item[0]["_index"];
            let fruit = item[0]["_chart"].data.labels[index];
            let votes = item[0]["_chart"].data.datasets[0].data[index];
        }
    }
});

Leave a comment