[Chartjs]-Determining which chart the user has clicked on

1👍

Inside the clicked function you can use getElementAtEvent(c) & _datasetIndex; to get the index of the chart data.After that use that index to get the data which is used to draw that line chart. In this example another field is added to the data and on click that name field is consoled. In this case you need to click on the chart circle

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
<div class="container">
  <div class="row my-3">
    <div class="col">
      <h4>Chart</h4>
    </div>
  </div>
  <div class="row my-2">
    <div class="col-md-12">
      <div class="card">
        <div class="card-body">
          <canvas id="chLine" height="100"></canvas>
        </div>
      </div>
    </div>
  </div>
</div>
let chLine = document.getElementById("chLine");

let chartData = {
  labels: ['l1', 'l2', 'l3', 'l4', 'l5', 'l6', 'l7', 'l8', 'l9'],
  datasets: [{
      name: 'First Chart',
      label: 'c1',
      data: [0.3, 0.4, 0.5, 0.35, 0.2, 0.5, 0.4, 0.55, 0.6],
      backgroundColor: 'transparent',
      borderColor: '#e6194b',
      borderWidth: 1,
      pointBackgroundColor: '#e6194b'
    },
    {
      name: 'Second Chart',
      label: 'c2',
      data: [0.7, 0.5, 0.2, 0.4, 0.6, 0.1, 0.88, 0.35, 0.45],
      backgroundColor: 'transparent',
      borderColor: '#3cb44b',
      borderWidth: 1,
      pointBackgroundColor: '#3cb44b',
      id: '1',
    }
  ]
}

if (chLine) {
  var myLineChart = new Chart(chLine, {
    type: 'line',
    data: chartData,
    options: {
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: false
          }
        }]
      },
      legend: {
        position: 'top',
        labels: {
          boxWidth: 5
        }
      },
      events: ['click'],
      onClick: clicked
    }
  });
}

function clicked(c, i, x) {
  let getDataSetIndex = this.getElementAtEvent(c)[0]._datasetIndex;
  console.log(chartData.datasets[getDataSetIndex].name)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
<div class="container">
  <div class="row my-3">
    <div class="col">
      <h4>Chart</h4>
    </div>
  </div>
  <div class="row my-2">
    <div class="col-md-12">
      <div class="card">
        <div class="card-body">
          <canvas id="chLine" height="100"></canvas>
        </div>
      </div>
    </div>
  </div>
</div>

Leave a comment