Return chosen label when clicking on any column of chart - Chart.Js

0

I have a Dashboard made in PHP and I use the Chart.js library.

In the Dashboard, I have some graphics that are fed into PHP, like in this example:

AndI'mhavingaquestion,whenIclickonsomecolumnofthegraph,IwanttogetitsnameanddisplayitinanJSalertmyself.

Inshort,whenIclickonabarbelongingtotheG1,Iwantittoshowanalertonitsname,Example:"You clicked on G1". The same with G4 or whatever else you have on the chart. How can I do this?

HTML Code:

      <div class="box-body">
          <canvas id="grupo" height="80px"></canvas>
      </div>

JS Code:

  var ctx5 = document.getElementById("grupo").getContext('2d');
  var container5 = new Chart(ctx5, {
     type: 'bar',
     data: {
        labels: label_grupo, // variavel alimentada pelo PHP
        datasets: [{
           label: "Total",
           backgroundColor: '#4dbd74',
           data: data_grupo_total, // variavel alimentada pelo PHP
        }, {
           label: "Alfa",
           backgroundColor: '#20a8d8',
           data: data_grupo_macho, // variavel alimentada pelo PHP
        }, {
           label: "Beta",
           backgroundColor: '#4c4c4c',
           data: data_grupo_femea, // variavel alimentada pelo PHP
        }]
     },
     options: {
        tooltips: {
           mode: 'index',
           intersect: false
        },
        scales: {
           yAxes: [{
              scaleLabel: {
                 display: true,
                 labelString: "Quantidade"
              }
           }],
           xAxes: [{
              gridLines: {
                 color: "rgba(0, 0, 0, 0)",
              },
              ticks: {
                 autoSkip: false,
                 fontSize: 11,
                 beginAtZero:true
              }
           }]
        },
        legend: {
           labels: {
              boxWidth: 12
           },
           position: "bottom",
        },
     }
  });
    
asked by anonymous 24.07.2018 / 16:48

1 answer

1

I think the more organized form would be like this, add the property onClick on object options

options:{
    onClick: minhaFuncao
}

and create its function:

function minhaFuncao(event, array){
    if(array[0]){
        // console.log(array);
    }
}

Documentation Chart.js #Events

var config = {};
var ctx = document.getElementById("canvas").getContext("2d");
var Charts= new Chart.Scatter(ctx, config);

canvas.onclick = function(event){
    var pontosAtivos = Charts.getElementsAtEvent(event);
    var primeiroPonto = pontosAtivos[0];

    if(primeiroPonto !== undefined){
        var label = Charts.data.labels[primeiroPonto._index];
        var value = Charts.data.datasets[primeiroPonto._datasetIndex].data[primeiroPonto._index];
        alert(label + ": " + value.x);
        alert(label + ": " + value.y);
     }
};
    
24.07.2018 / 18:23