3๐
โ
You can define an onClick
event handler, which unfortunately is poorly documented. In your case, it would look as follows, onBarClicked
being your own function that is invoked with company
and category
.
options: {
...
onClick: event => {
const datasetIndex = chart.getElementAtEvent(event)[0]._datasetIndex;
const model = chart.getElementsAtEvent(event)[datasetIndex]._model;
onBarClicked(model.datasetLabel, model.label);
}
}
Please have a look at your amended code below:
function onBarClicked(company, category) {
console.log('company = ' + company + ", category = " + category);
}
const default_colors = ['green', 'blue'];
function addGroupBarChart(data, labels) {
arr = []
data.forEach((d, i) => {
company = Object.keys(d)[0];
values = d[company]['data'];
dataset_company = {
label: company,
backgroundColor: default_colors[i],
data: values
};
arr.push(dataset_company);
});
let data_grouped = {
labels: labels,
datasets: arr
};
var chart = new Chart("bar-chart-group", {
type: "bar",
data: data_grouped,
options: {
title: {
display: false,
text: "Sentiment by category"
},
onClick: event => {
const datasetIndex = chart.getElementAtEvent(event)[0]._datasetIndex;
const model = chart.getElementsAtEvent(event)[datasetIndex]._model;
onBarClicked(model.datasetLabel, model.label);
}
}
});
}
const data = [{"Air France":{"data":[0.1, -0.2, 0.3, -0.1, 0.1]}},
{"Lufthansa":{"data":[0.3, -0.2, 0.5, 0.2, 0.1]}}];
const labels = ["company", "food", "luggage", "punctuality", "staff"];
addGroupBarChart(data, labels);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<canvas id="bar-chart-group" height="80"></canvas>
1๐
In the new version of Chart.js, the below code would work.
const ctx = $('#monitor');
monitorChart = new Chart(ctx, config);
ctx.on('click', function(evt) {
const points = monitorChart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true);
if (points.length) {
const firstPoint = points[0];
const label = monitorChart.data.labels[firstPoint.index];
const slabel = monitorChart.data.datasets[firstPoint.datasetIndex].label;
const value = monitorChart.data.datasets[firstPoint.datasetIndex].data[firstPoint.index];
console.log(label, slabel, value);
}
});
You can check Here!
0๐
the answer of @risingagain seems to be made for jquery.
for vanillajs, as per the actual documentation at , the event should stay on the canvas element itself, so iโll rewrite his (otherwise working) example:
const ctx = $('#monitor');
let chart = new Chart(ctx, config);
chart.ctx.canvas.onclick = (evt) => {
const points = chart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true);
if (points.length) {
const firstPoint = points[0];
const label = chart.data.labels[firstPoint.index];
const slabel = chart.data.datasets[firstPoint.datasetIndex].label;
const value = chart.data.datasets[firstPoint.datasetIndex].data[firstPoint.index];
console.log(label, slabel, value);
}
};
Source:stackexchange.com