ChartJs 2.0 How do I obtain point information being clicked upon?
I have a graph with multiple data sets. Using the proposed getElementsAtEvent(evt)
function, returns all data sets at a given x position but not only the single dataset index that I clicked on. So, there is no possibility to identify the individual data set.
To get only the single point clicked on:
const activePoint = chartObj.getElementAtEvent(event);
const datasetIndex = activePoint[0]._datasetIndex;
const itemIndex = activePoint[0]._index;
Notice the missing "s" in getElementAtEvent()
compared to getElementsAtEvent()
.
Another way to achieve this in ChartJS 2.0 is to use the lastActive property of the radar chart.
var myRadar = new Chart(document.getElementById("myChart"), config);
Chart.defaults.global.responsive = true;
Chart.defaults.global.hover.mode = 'single';
document.getElementById("myChart").onclick = function (evt) {
var activePoint = myRadar.lastActive[0];
if (activePoint !== undefined) {
var datasetIndex = activePoint._datasetIndex;
var index = activePoint._index;
var datasetName = config.data.datasets[datasetIndex].label;
var title = config.data.labels[index];
var dataValue = config.data.datasets[datasetIndex].data[index];
alert("Dataset Name: [" + datasetName + "] title: [" + title + "] value: [" + dataValue + "]");
}
};
You should be able to use the getElementsAtEvent
method, like so
document.getElementById("myChart").onclick = function(evt){
var activePoints = myRadar.getElementsAtEvent(evt);
// use _datasetIndex and _index from each element of the activePoints array
};
Fiddle - http://jsfiddle.net/uwaszvk7/