Reputation: 1774
I have a bar chart where on a click of any bar, the data is displayed in a tooltip. I need the tooltip data in the onClick
function.
Following is my code for the bar chart:
var tool = new Chart(canvas, {
type: 'bar',
data: data,
options: {
legend: {
display: true,
labels: {
fontColor: 'rgb(255, 99, 132)'
},
position : 'bottom'
},
title: {
display: true,
text: title
},
scales: {
xAxes: [{stacked: true,barPercentage: 5.0,
categoryPercentage: 0.2}],
yAxes: [{
stacked: true,
ticks: {
beginAtZero: true
},
barPercentage: 0.3
}]
},
events: [ "click"],
onClick: function(event, array){
console.log("tool.data:",tool.tooltip);
}
}
});
I want the data in my click function like "missed", "medium", 78.
Upvotes: 0
Views: 2640
Reputation: 32859
You can use the following onClick
function to get tooltip's data :
onClick: function(event, element) {
var activeElement = element[0];
var data = activeElement._chart.data;
var barIndex = activeElement._index;
var datasetIndex = activeElement._datasetIndex;
var datasetLabel = data.datasets[datasetIndex].label;
var xLabel = data.labels[barIndex];
var yLabel = data.datasets[datasetIndex].data[barIndex];
console.log(datasetLabel, xLabel, yLabel);
}
also, you would need to set the hover
mode of chart to nearest
to get it working properly :
hover: {
mode: 'nearest'
}
see a working example.
Upvotes: 4