I'm trying to add a click event, using javascript, to each column of a barchart in Chart.js

airider74 :

I've been trying to add a click event to each column in a bar chart using Chart.js. What I'm trying to figure out is how to make a click event on each column execute the code I want.

The goal for this is when a user clicks on a particular bar of the chart, it executes a php form submit that takes them to another page on the website.

The bar chart data is populated from an SQL database via php when the user goes to the page.

Here's an example of the code I have so far ...

<canvas id="briskChart" style="margin:auto;display:block;background-color:white;border-style:solid;border-width:1px;padding:10px;"></canvas>

<script>
var red = <?=json_encode($count1[0]);?>;
var yellow = <?=json_encode($count2[0]);?>;
var green = <?=json_encode($count3[0]);?>;
var blue = <?=json_encode($count4[0]);?>;
var grey = <?=json_encode($count5[0]);?>;

var dept = <?=json_encode($row['dept']);?>;


var c1 = document.getElementById('briskChart')
var ctx = c1.getContext("2d");
var briskChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Yellow', 'Green', 'Watch', 'Retired'],
        datasets: [{
            data: [red, yellow, green, blue, grey],
            backgroundColor: [
                'rgba(255, 0, 0, 0.4)',
                'rgba(255, 216, 0, 0.4)',
                'rgba(0, 255, 0, 0.4)',
                'rgba(0, 0, 255, 0.4)',
                'rgba(160, 160, 160, 0.4)'
            ],
            borderColor: [
                'rgba(255, 0, 0, 1)',
                'rgba(255, 216, 0, 1)',
                'rgba(0, 255, 0, 1)',
                'rgba(0, 0, 255, 1)',
                'rgba(160, 160, 160, 1)'

            ],
            borderWidth: 1
        }]

    },
    options: {
    onClick: event => {
        document.bred.submit();
        },
        title: {
            display: true,
            fontSize: 24,
            text: dept + ' Dept Risk Summary',
            fontColor: '#000000'
        },
        legend: {
            display: false,
        },
        scales: {
                xAxes: [{
                        display: true,
                        gridLines: {color: '#000000'},
                        ticks: {
                            fontColor: "black",
                            fontSize: 16
                            }
                        }],
                yAxes: [{
                        display: true,
                        gridLines: {color: '#000000'},
                        ticks: {
                            beginAtZero: true,
                            fontColor: "black",
                            fontSize: 16,
                            stepSize: 1
                            }
                        }],
        }
    }
});

</script>

Here is the html:

<form action='../php/bred.php' method='POST' name='bred'>
</form>

The documentation for Chart.js is very limited regarding click events. For each data series, when the column is clicked on, I want to run a corresponding document.[form name].submit to take the user to that new page.

If anybody has any experience doing this with Chart.js and could point me in the right direction, I'd be eternally grateful.

AndroidNoobie :

You can create a click handler that retrieves the x and y values from the chart. Then, using that data, you could send a GET or POST request to your PHP script.

Example for getting the values from the bar chart (the key here is to look at the onClick function):

var red, yellow, green, blue, grey, dept = "";

var c1 = document.getElementById('briskChart')
var ctx = c1.getContext("2d");
var briskChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Yellow', 'Green', 'Watch', 'Retired'],
    datasets: [{
      data: [1, 2, 3, 4, 5],
      backgroundColor: [
        'rgba(255, 0, 0, 0.4)',
        'rgba(255, 216, 0, 0.4)',
        'rgba(0, 255, 0, 0.4)',
        'rgba(0, 0, 255, 0.4)',
        'rgba(160, 160, 160, 0.4)'
      ],
      borderColor: [
        'rgba(255, 0, 0, 1)',
        'rgba(255, 216, 0, 1)',
        'rgba(0, 255, 0, 1)',
        'rgba(0, 0, 255, 1)',
        'rgba(160, 160, 160, 1)'

      ],
      borderWidth: 1
    }]

  },
  options: {
    onClick: function(c, i) {
      element = i[0];  // the chart element you clicked on
      var xValue = this.data.labels[element._index];  // the x-value of the bar
      var yValue = this.data.datasets[0].data[element._index];  // the y-value of the bar
      console.log(xValue);
      console.log(yValue);
      // then, here, you could send a GET/POST request to your PHP function
    },
    title: {
      display: true,
      fontSize: 24,
      text: dept + ' Dept Risk Summary',
      fontColor: '#000000'
    },
    legend: {
      display: false,
    },
    scales: {
      xAxes: [{
        display: true,
        gridLines: {
          color: '#000000'
        },
        ticks: {
          fontColor: "black",
          fontSize: 16
        }
      }],
      yAxes: [{
        display: true,
        gridLines: {
          color: '#000000'
        },
        ticks: {
          beginAtZero: true,
          fontColor: "black",
          fontSize: 16,
          stepSize: 1
        }
      }],
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<canvas id="briskChart">
</canvas>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=198708&siteId=1