4

I want to make my chart js bar clickable. I want to add click features such as links. No idea how to proceed. Have read documentation times 10...

<script> var ctx = document.getElementById('myChart').getContext('2d');


var myChart = new Chart(ctx, {
 type: 'bar',
 data: {
labels: ['Now', '-1h', '-2h', '-3h', '-4h', '-5h', '-6h', '-7h', '-8h', '-9h', '-10h', '-11h', '-12h', '-13h', '-14h', '-15h', '-16h', '-17h', '-18h', '-19h', '-20h', '-21h', '-22h', '-23h'],
datasets: [{
  label: 'Litraa',
  data: [<?php echo "$chart_readings[0]";?>, <?php echo "$chart_readings[1]";?>, <?php echo "$chart_readings[2]";?>, <?php echo "$chart_readings[3]";?>, <?php echo "$chart_readings[4]";?>, <?php echo "$chart_readings3[5]";?>, <?php echo "$chart_readings3[6]";?>, <?php echo "$chart_readings[7]";?>, <?php echo "$chart_readings[8]";?>, <?php echo "$chart_readings[9]";?>, <?php echo "$chart_readings[10]";?>, <?php echo "$chart_readings[11]";?>, <?php echo "$chart_readings[12]";?>, <?php echo "$chart_readings[13]";?>, <?php echo "$chart_readings[14]";?>, <?php echo "$chart_readings[15]";?>, <?php echo "$chart_readings[16]";?>, <?php echo "$chart_readings[17]";?>, <?php echo "$chart_readings[18]";?>, <?php echo "$chart_readings[19]";?>, <?php echo "$chart_readings[20]";?>, <?php echo "$chart_readings[21]";?>, <?php echo "$chart_readings[22]";?>, <?php echo "$chart_readings[23]";?>],
  backgroundColor: "rgb(255, 255, 255)"
}]
},
   options: {
    tooltips: {
        mode: 'label'
    }
}
});
/*Global settings*/
Chart.defaults.global.defaultFontColor = '#fff';
</script>
Ville
  • 105
  • 2
  • 2
  • 8

1 Answers1

27

If you are using chart.js version 2.4+ (maybe earlier), there is a onclick event that is very useful. I'm using it on a stacked bar chart, so it should work for you too. You can find it under common chart configuration in the documentation. (See: https://www.chartjs.org/docs/latest/charts/bar.html#stacked-bar-chart)

options:{
    onClick: graphClickEvent
}

function graphClickEvent(event, array){
    if(array[0]){
       foo.bar;
    }
}

Hope this helps.

Léa Gris
  • 17,497
  • 4
  • 32
  • 41
Tom Glover
  • 2,996
  • 23
  • 23
  • I tryet to this. But something is still wrong with my edit. Could you see it below? – Ville Jan 28 '17 at 11:48
  • 3
    Just what I needed, thanks! in case it's not obvious 'array[0]._index' will return the index of the clicked bar – Verno Aug 17 '17 at 09:02
  • Thanks for the info.Other keys in arrays[0]: "_chart,_datasetIndex,_index,hidden,_xScale,_yScale,_model,_view,_start,$previousStyle". The keys can be retrieved by Object.keys(array[0]). – akash Jan 24 '20 at 20:05
  • Thanks! I use React JS, I knew onClick on a stacked bar chart would work, but don't know exactly what's the right format. I had option = {{ onclick: handleOnClick() }}, it didn't work. after couple hours, I had to change to option = {{ onClick: handleOnClick }}, it finally works!! – stoneshishang Jun 17 '21 at 13:36