Skip to content
Advertisement

Chart Js clickable bar

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>

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement