score:62
I managed to find the answer to my question by looking through the Chart.js source code.
Provided at line 3727 of Chart.js, Standard Build, is the method .getElementAtEvent
. This method returns me the "chart element" that was clicked on. There is sufficent data here to determine what data to show in a drill-down view of the dataset clicked on.
On the first index of the array returned by chart.getElementAtEvent
is a value _datasetIndex
. This value shows the index of the dataset that was clicked on.
The specific bar that was clicked on, I believe, is noted by the value _index
. In my example in my question, _index
would point to One
in chart_config.data.labels
.
My handleClick
function now looks like this:
function handleClick(evt)
{
var activeElement = chart.getElementAtEvent(evt);
..where chart
is the reference of the chart created by chart.js when doing:
chart = new Chart(canv, chart_config);
The specific set of data that was selected by the click can therefore be found as:
chart_config.data.datasets[activeElement[0]._datasetIndex].data[activeElement[0]._index];
And there you have it. I now have a datapoint that I can build a query from to display the data of the bar that was clicked on.
AUGUST 7TH, 2021. UPDATE
There is now a method for what we are looking for. Take a look at here
score:0
Let's say that you declared a chart using a method like so:
window.myBar = new Chart({chart_name}, {
type: xxx,
data: xxx,
events: ["click"],
options: {
...
}
});
A good way of declaring onclick events would involve listening for the canvas click, like so:
({chart_name}.canvas).onclick = function(evt) {
var activePoints = myBar.getElementsAtEvent(evt);
// let's say you wanted to perform different actions based on label selected
if (activePoints[0]._model.label == "label you are looking for") { ... }
}
score:0
In the chart options for Chart.js v3.5.1 which is latest
Check below sample code
let enterpriseChartOptions = {
responsive:true,
maintainAspectRatio: false,
onClick: (c,i) => {
console.log('Get the underlying label for click,', c.chart.config._config.data.labels[i[0].index]);
},
plugins: {
title:{
text:'Enterprise Dashboard (Health Status of 10 stores) updated every 30 minutes',
fontSize:20
},
},
scales: {
x: {
display: true,
type: 'category',
position: 'right',
ticks: {
padding: 8,
},
},
y: {
display: true,
ticks: {
callback: function(val, index) {
// Show the label
return val < 1 ? "All good" : (val < 2 && val >=1) ? "Warning": val === 2 ? "Critical" : "";
},
//color: 'red',
stepSize: 1,
padding: 8
}
}
},
layout: {
padding: {
left: 20,
right: 20,
top: 25,
bottom: 0
}
},
};
score:0
var employeeDetailsCtx = document.getElementById("employee-details").getContext("2d");
var employee_details_data = {
labels: ["Late Present", "On Leave", "Training", "Tour"],
datasets: [{
label: "Officer",
backgroundColor: "#5A8DEE",
data: [
...
]
}, {
label: "Staff",
backgroundColor: "#4BC0C0",
data: [
...
]
}]
};
var myoption = {
tooltips: {
enabled: true
},
hover: {
animationDuration: 1
},
onClick: function (evt, i) {
var activePoint = employeeDetailsBarChart.getElementAtEvent(evt)[0];
var data = activePoint._chart.data;
var datasetIndex = activePoint._datasetIndex;
var label = data.datasets[datasetIndex].label;
var value = data.datasets[datasetIndex].data[activePoint._index];
e = i[0];
var x_value = this.data.labels[e._index];
console.log(x_value)
console.log(label)
console.log(value)
},
animation: {
duration: 1,
onComplete: function () {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.textAlign = 'center';
ctx.fillStyle = "rgba(0, 0, 0, 1)";
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
ctx.fillText(data, bar._model.x, bar._model.y - 5);
});
});
}
}
};
var employeeDetailsBarChart = new Chart(employeeDetailsCtx, {
type: 'bar',
data: employee_details_data,
options: myoption
});
score:2
I was able to make this work in another way. Might not be supported, but sometimes, I find that neither the label nor the value is adequate to get me the necessary information to populate a drill-through.
So what I did was add a custom set of attributes to the data:
var ctx = document.getElementById("cnvMyChart").getContext("2d");
if(theChart != null) {theChart.destroy();}
theChart = new Chart(ctx, {
type: typ,
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datakeys: ["thefirstone","thesecondone","thethirdone","thefourthone","thefifthone","thesixthone"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
...etc
Then when I need to push the drillthrough key into another ajax call, I was able to get it with this:
var theDrillThroughKey = theChart.config.data.datakeys[activePoints[0]._index];
So I'm really not sure that it's appropriate to be adding custom elements into the data for the Chart, but it's working so far in Chrome, IE and Firefox. I needed to be able to put more information into the drillthrough than I really wanted displayed.
Example of the full thing: https://wa.rrdsb.com/chartExamples
Thoughts?
score:2
I had the same problem with multiple datasets, and used this workaround:
var clickOnChart = function(dataIndex){
...
}
var lastHoveredIndex = null;
var chart_options = {
...
tooltips: {
...
callbacks: {
label: function(tooltipItem, chart) {
var index = tooltipItem.datasetIndex;
var value = chart.datasets[index].data[0];
var label = chart.datasets[index].label;
lastHoveredIndex = index;
return value + "€";
}
}
},
onClick:function(e, items){
if ( items.length == 0 ) return; //Clicked outside any bar.
clickOnChart(lastHoveredIndex);
}
}
score:3
Well done! This seems to return the data value being charted though, which in many cases might be possible to appear more than once, thus making it unclear what was clicked on.
This will return the actual data label of the bar being clicked on. I found this more useful when drilling down into a category.
chart_config.data.labels[activeElement[0]._index]
score:3
Chartjs V3.4.1
This is what worked for me in v3, after looking at solutions for older versions:
const onClick = (event, clickedElements) => {
if (clickedElements.length === 0) return
const { dataIndex, raw } = clickedElements[0].element.$context
const barLabel = event.chart.data.labels[dataIndex]
...
}
raw
is the value of the clicked bar.barLabel
is the label of the clicked bar.
You need to pass the onClick
to the bar chart config:
const barConfig = {
...
options: {
responsive: true,
onClick,
...
}
}
score:6
You can use onClick like this.
var worstCells3GBoxChart = new Chart(ctx, {
type: 'bar',
data: {
labels: lbls,
datasets: [{
label: 'Worst Cells by 3G',
data: datas,
backgroundColor: getColorsUptoArray('bg', datas.length),
borderColor: getColorsUptoArray('br', datas.length),
borderWidth: 1
}]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
onClick: function (e) {
debugger;
var activePointLabel = this.getElementsAtEvent(e)[0]._model.label;
alert(activePointLabel);
}
}
});
score:11
I found this solution at https://github.com/valor-software/ng2-charts/issues/489
public chartClicked(e: any): void {
if (e.active.length > 0) {
const chart = e.active[0]._chart;
const activePoints = chart.getElementAtEvent(e.event);
if ( activePoints.length > 0) {
// get the internal index of slice in pie chart
const clickedElementIndex = activePoints[0]._index;
const label = chart.data.labels[clickedElementIndex];
// get value by index
const value = chart.data.datasets[0].data[clickedElementIndex];
console.log(clickedElementIndex, label, value)
}
}
}
score:55
Hi this is the click event under options which is getting values from x and y-axis
onClick: function(c,i) {
e = i[0];
console.log(e._index)
var x_value = this.data.labels[e._index];
var y_value = this.data.datasets[0].data[e._index];
console.log(x_value);
console.log(y_value);
}
Source: stackoverflow.com
Related Query
- Chart.js: Bar Chart Click Events
- Click event on stacked bar chart - ChartJs
- Chart.js click on labels, using bar chart
- Click on interactive chart.js bar chart and get value for labels and groups in JS
- Group bar chart in ReactChartJS2 click particular element
- I need to increase data in a bar chart by one with a button click
- Can we remove bar chart line on click on pie chart legend label?
- Add a click event to the bar chart of chartjs
- How to clear a chart from a canvas so that hover events cannot be triggered?
- Click events on Pie Charts in Chart.js
- chart js 2 how to set bar width
- Chartjs Bar Chart showing old data when hovering
- Chartjs v2.0: stacked bar chart
- Horizontal stacked bar chart with chart.js
- Chart.js Bar Chart - how to chart bars from 0
- Horizontal bar chart in chart.js
- How to add an on click event to my Line chart using Chart.js
- Vertical stacked bar chart with chart.js
- Changing fontFamily on ChartJS bar chart
- Chart.js: bar chart first bar and last bar not displaying in full
- How to put rounded corners on a Chart.js Bar chart
- Chart.js: Dynamic Changing of Chart Type (Line to Bar as Example)
- chartjs : how to set custom scale in bar chart
- Chartjs 2 - Stacked bar and unstacked line on same chart with same y axis
- Chartjs Bar Chart Legend
- Add DataSet Bar Chart - Chart.JS
- Detecting hover events over parts of a chart using Chart.js
- ChartJS add tooltip to a grouped bar chart
- Chart.js setting maximum bar size of bar chart
- How to add second Y-axis for Bar and Line chart in Chart.js?
More Query from same tag
- How to remove trial version watermark in canvasjs using Jquery (without license)
- Data with x and y data, missing data are not taken into account
- Download Chart.js graph from view
- How to add on click event to chart js
- Chart.js Customize tool tip to show more data
- Chart.js add icon at the top of bar
- Multiple chart on one page using chart.js and Flask app
- how to creat a dynamic datasets and new dynamic multi yAxes
- How to show/hide animation when legend clicked chart js
- Chart.js drawing only in the top of canvas
- Scatter plot in Chart.js with annotations
- Background color hides Y labels
- chartjs show 24 hours in line chart
- Multiples values in yAxes with same xAxes
- Javascript: Showing bedtimes in Chart.js
- chart.js - Supplied parameters do not match any signature of call target (angular2)
- chartjs creating equilvant background like in chartjs.org
- Can I arrange labels of legend in Doughnut chart one by one?
- Get data from dynamic ID for Chart.js
- Display Charts based on year select in django
- Display Date Label in axes - chart js/ng2 charts
- Update Chart JS data dynamically and add new data, remove old data to create timeline "like" chart
- zeroLineColor and zeroLineWidth not working for the x-axis in Chartjs
- How to use log scale with Chart Kick?
- dynamic charts using chart.js
- How to append more data in tooltip of graph in chart.js
- Chart.js - Toggle visibility of charts
- Chartjs v2.0: stacked bar chart
- How to make the whole <canvas> element in Chart.js V3.7.0 display cursor as pointer on hover?
- Chartjs: dynamic data (array) not working