Identify which chartJs chart was clicked on

I have several charts on a page. They are created dynamically. I need to identify in the click event, or somehow, which chartwas clicked on.

Maybe it’s parent element? The canvas ‘canvas1’ or ‘canvas2′ or ..’canvas10’,is in a bootstrap column of id ‘col1’ or ‘col2′ or ..’col10’ I can’t get to pass a parameter via the click function

onClick: OnDrillDownClick(evt, canvasIdParam)

Each chart of course has a different canvas but all are defined as demoChart.

var canvasChart = $("#canvas" + canvasId).get(0).getContext("2d");
demoChart = new Chart(canvasChart,

Using the ‘OnClick’ function provided, e.g.

function OnDrillDownClick(evt)
{
    var activePoints = demoChart.getElementsAtEvent(evt);
    ...etc
}

I just need to identify which chart was clicked on as I keep an array of the created charts i.e.

var chartRec = {
        CanvasId: canvasId,
        Chart: demoChart
    };

    chartsArray.push(chartRec);

Many thanks

Answer

You can get the canvas id from the click event like this:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    onClick: (evt) => {
      console.log(evt.target.getAttribute('id'))
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>
</body>

Leave a Reply

Your email address will not be published. Required fields are marked *