Chartjs-Chartjs Overlap click function doesnt work

1👍

You explicitly reference dataset 0. You need to pass the dataset index like so:

canvas.onclick = function(evt) {
  var activePoints = myLineChart.getElementAtEvent(evt);
  //console.log(activePoints);
  if (activePoints[0]) {
    var chartData = activePoints[0]['_chart'].config.data;
    var idx = activePoints[0]['_index'];

    var label = chartData.labels[idx];

    // change the following line...
    //var value = chartData.datasets[0].data[idx];
    // to this:
    var value = chartData.datasets[activePoints[0]._chart.tooltip._active[0]._datasetIndex].data[idx];

    var url = "Mês:" + label + " Valor: " + value;
    alert(url);
  }
};

Edit: Fully working example.

var canvas = document.getElementById("lineChart");
var ctx = canvas.getContext('2d');


    canvas.onclick = function(evt) {
      var activePoints = myLineChart.getElementAtEvent(evt);
      console.log(activePoints);
      if (activePoints[0]) {
        var chartData = activePoints[0]['_chart'].config.data;
        var idx = activePoints[0]['_index'];

        var label = chartData.labels[idx];
        //var value = chartData.datasets[0].data[idx];
        var value = chartData.datasets[activePoints[0]._chart.tooltip._active[0]._datasetIndex].data[idx];

        var url = "Mês:" + label + " Valor: " + value;
        alert(url);
      }
    };


var data = {
  labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
  datasets: [{
      label: "Stock A",
      fill: false,
      lineTension: 0.1,
      backgroundColor: "rgba(225,0,0,0.4)",
      borderColor: "red", 
      borderCapStyle: 'square',
      pointBorderWidth: 0.1,
      pointHoverRadius: 6,
      pointHoverBorderWidth: 2,
      pointRadius: 1,
      data: [2, 59, 80, 81, 56],
      spanGaps: false

    }, {
      label: "Stock B",
      fill: false,
      lineTension: 0.1,
      backgroundColor: "black",
      borderColor: "black", 
      borderCapStyle: 'square',
      pointBorderWidth: 0.1,
      pointHoverRadius: 6,
      pointHoverBorderWidth: 2,
      pointRadius: 1,
      data: [0, 20, 60, 95, 64],
      spanGaps: false
    }

  ]
};

// Chart declaration:
var myLineChart = new Chart(ctx, {
  type: 'line',
  data: data,
  options: {
    tooltips: {
         enabled: true
    }
  }

});
body{
  background-color: #666;
}

#lineChart{
  background-color: wheat;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<div class="container">
  <br />
  <div class="row">
    <div class="col-md-1"></div>
    <div class="col-md-10">
<!--       Chart.js Canvas Tag -->
      <canvas id="lineChart"></canvas>
    </div>
    <div class="col-md-1"></div>
  </div>
</div>

Leave a comment