I am a beginner to Chart.js and I am trying to create click events when a chart is created.
I am trying to access all the elements of a bar when it is clicked on, but right now, the onClick method is not even running properly. The chart is rendering just fine - any html should not be needed as the canvas is created in the code. I would appreciate help in order to solve this problem
controller($state, $scope, $rootScope) {
$scope.myChart;
....
$scope.go = function myFunc() {
document.getElementById("chartContainer").innerHTML = ' ';
document.getElementById("chartContainer").innerHTML = '<canvas style="margin-top: 10px; padding-top: 20px; height:90% ; background-color: ' + vm.options.backgroundColor + '; " id="myChart" click="onClick"></canvas>';
var ctx = document.getElementById("myChart").getContext('2d');
render($scope.myChart, ctx, vm.options.barColor, vm.options.backgroundColor, labelVal, value);
};
$scope.onClick = function (evt) {
console.log("Testing");
};
}
var render = function createChart(myChart, ctx, barColor, backgroundColor, labels, values) {
myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
backgroundColor: barColor,
data: values,
}]
},
options: {
events: ['click'],
chartArea: {
backgroundColor: backgroundColor,
},
global: {
responsive: true,
maintainAspectRatio: false,
},
scaleBeginAtZero: true,
maintainAspectRatio: false,
scales: {
xAxes: [{
ticks: {
autoSkip: false,
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
min: 0
}
}]
}
}
});
}
TRY adding the following on-click event handler in your chart options ...
options: {
onClick: function(e) {
var element = this.getElementAtEvent(e);
if (element.length) {
console.log(element[0])
}
},
...
}
This should work as far as I can tell
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With