Charles Graham Charles Graham - 1 month ago 9
Javascript Question

How can I get bar height on click in chartjs 2.6.0

I have a bar chart. When I click on one of the bar, I want it to return its height. I have tried adding a mouse clcik event to the chart but that didn't work. So how can I get the bar height when it is clicked?

Here is the code that I use to create the chart..

new Chart(ctx, {
type: 'bar',
data: {
labels: cm_labels,
datasets: [{
label: 'Number of votes',
data: cm_data,
backgroundColor: 'red'
}]
},
}}


Thanks for any help!

Answer Source

First, add onClick method to your chart options, which will fire when the chart detects any click on itself.

Then to get the actual bar height when the onClick method is fired, you can use getElementAtEvent() method, as such :

onClick: function(event) {
   var bar = this.getElementAtEvent(event);
   if (!bar.length) return; //return if not clicked on bar
   var barHeight = bar[0].height();
   alert(barHeight);
}

ᴅᴇᴍᴏ

var chart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
      datasets: [{
         label: 'LINE',
         data: [3, 1, 4, 2, 5],
         backgroundColor: 'rgba(0, 119, 290, 0.2)',
         borderColor: 'rgba(0, 119, 290, 0.6)'
      }]
   },
   options: {
      onClick: function(event) {
         var bar = this.getElementAtEvent(event);
         if (!bar.length) return; //return if not clicked on bar
         var barHeight = bar[0].height();
         alert(barHeight);
      },
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>