Chartjs-How can i launch a modal after clicking each bar in Bar chart in Chartjs and also how can i get its data?

0👍

This is quite straightforward and is documented at the Chart.js API page. Below is a working snippet adapted from the official example:

let canvas = document.getElementById('canvas');

let myChart = new Chart(canvas, {
  type: 'bar',
  data: {
    labels: ['a', 'b', 'c', 'd'],
    datasets: [{
      data: [0, 2, 4, 8]
    }]
  }
});

canvas.addEventListener('click', function(evt) {
  var firstPoint = myChart.getElementAtEvent(evt)[0];
  if (firstPoint) {
    var label = myChart.data.labels[firstPoint._index];
    var value = myChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];

    alert('Label: ' + label + "\nValue: " + value);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.min.js"></script>
<canvas id="canvas"></canvas>

Leave a comment