score:8
Accepted answer
You can use getElementAtEvent()
method to get only one dataset returned. Then you can apply further logic to detect which bar is clicked on.
ᴅᴇᴍᴏ
var barChartData = {
labels: ["Jan", "Feb", "March"],
datasets: [{
label: "Quoted",
backgroundColor: "#FF7228",
data: [50, 20, 70],
}, {
label: "Accepted",
backgroundColor: "#FFCC8C",
data: [30, 10, 20],
}]
};
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
onClick: function(e) {
var bar = this.getElementAtEvent(e)[0];
var index = bar._index;
var datasetIndex = bar._datasetIndex;
// check which bar is clicked
if (index == 0 && datasetIndex == 0) alert('First BAR Clicked!');
else if (index == 0 && datasetIndex == 1) alert('Second BAR Clicked!');
else if (index == 1 && datasetIndex == 0) alert('Third BAR Clicked!');
else if (index == 1 && datasetIndex == 1) alert('Fourth BAR Clicked!');
else if (index == 2 && datasetIndex == 0) alert('Fifth BAR Clicked!');
else if (index == 2 && datasetIndex == 1) alert('Sixth BAR Clicked!');
}
},
responsive: true,
legend: {
position: 'top',
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>
score:1
Building on Grunt's answer more, if you want to know the underlying data, so consider mine only the onclick code:
var barChartData = {
labels: ["Jan", "Feb", "March"],
datasets: [{
label: "Quoted",
backgroundColor: "#FF7228",
data: [50, 20, 70],
}, {
label: "Accepted",
backgroundColor: "#FFCC8C",
data: [30, 10, 20],
}]
};
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
onClick: function(e) {
var bar = this.getElementAtEvent(e)[0];
if (bar != undefined) {
var index = bar._index;
var datasetIndex = bar._datasetIndex;
alert(barChartData.datasets[datasetIndex].data[index].x +
', ' + barChartData.datasets[datasetIndex].data[index].y);
}
}
},
responsive: true,
legend: {
position: 'top',
},
});
score:1
Updated answer for Chart.js 3.7
Use chart.getElementsAtEventForMode(evt, ...)
. See documentation.
const barChartData = {
labels: ["Jan", "Feb", "March"],
datasets: [{
label: "Quoted",
backgroundColor: "#FF7228",
data: [50, 20, 70],
}, {
label: "Accepted",
backgroundColor: "#FFCC8C",
data: [30, 10, 20],
}]
};
const ctx = document.getElementById("canvas").getContext("2d");
const chart = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
onClick: function (evt, elements, chart) {
const bars = chart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true);
if (bars.length === 0) return; // no bars
const bar = bars[0];
// Get index and label text
const index = bar.index;
const label = chart.data.labels[index];
// Get clicked bar dataset index
const datasetIndex = bar.datasetIndex;
const isQuotedBar = datasetIndex === 0; // 0 is the first dataset ("Quoted")
alert(`${isQuotedBar ? 'Quoted' : 'Accepted'} bar was clicked, for ${label}.`);
}
},
responsive: true,
legend: {
position: 'top',
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="canvas"></canvas>
Source: stackoverflow.com
Related Query
- ChartJs how to get from mulitiple dateset which dataset bar is clicked
- React - how to get array from store before first render and use it as dataset for ChartJS
- Angular chart.js onClick is not working - how to get all elements of a bar when it is clicked on
- How do I add time sourced from an external source as an X axis to a ChartJS graph?
- how to determine which bar was clicked on a chart js
- How to get Data from API to display chart using chartjs in Vuejs
- chartjs how to update dynamically data from database(Chartjs cant get the data)
- How to get clicked bar chart tooltip data?
- how to insert dynamic data from sql into chartjs stacked bar chart javascript
- How to know which bar is clicked on chart.js bar chart with multiple data?
- How to keep side bars in Chartjs bar graph from clipping?
- How do you get the width of a datalabel from the Chartjs plugin after the chart animates?
- How to get ChartJs object from dynamically created chart
- How Can I Get An Instance of a ChartJS Bar Chart Using Angular
- How to get dataset from MySQL using Flask?
- How to get the image from graph created using chartjs
- Trying to get _index of clicked bar in ChartJS
- how to filter dataset from labels using ChartJS
- Chartjs bar chart trying to get labels from datasets
- How can i launch a modal after clicking each bar in Bar chart in Chartjs and also how can i get its data?
- How to access custom property in dataset object in Bar Chart in React ChartJS 2?
- Chart.js how to get Combined Bar and line charts?
- How to disable a tooltip for a specific dataset in ChartJS
- How to modify bar width in Chartjs 2 bar charts
- ChartJs 2.0 How do I obtain point information being clicked upon?
- Chart.js Bar Chart - how to chart bars from 0
- How get sum of total values in stackedBar ChartJs
- chartjs : how to set custom scale in bar chart
- ChartJS bar chart with legend which corresponds to each bar
- How to change the cursor to a pointer when I hover over a bar in a ChartJS bar chart?
More Query from same tag
- I am having this error in charts v3 chartjs-chart-treemap: fontColor does not exist in type 'ChartDataset<"treemap", TreemapDataPoint[]>
- How to use Chart.js to draw solid points
- Set max value of chart.js bar chart
- Change chart values from API
- Hiding Chart.js line, but showing it's data in the tooltip
- Chart.js, set a max value
- how to draw line graph with line animation from left to right using chartjs?
- Chartjs xaxes tick min
- Chart.js v2 overwrite draw function
- Changing color of specific ChartJS - AngularChartJS point
- How to plot data coming async in a chartjs chart
- Error in compilation for chart.js Expected method shorthand in object literal ('{label() {...}}'
- ChartJS + twig symfony
- Want to show the dataset labels
- Chart.js with plotting durations against dates
- Creating a real time line chart using chartjs and firebase realtime db
- Chart JS chart not rendering in ArcGIS popup when using navigation arrows
- Horizontal bar chart in chart.js
- Canvas size not changing
- Angular and ChartJS colors
- Chart JS Re-Animate chart with onclick
- In react hooks, how can i pass the filtered values to the chart?
- React - How can I pass API data from one component to another in a different js file?
- Charts not showing in wicked pdf
- MYSQL Query and Chart.js and PHP
- Color the bars using Angular-Chart.js
- Issues with react-chartjs-2
- Attach onAnimationComplete for Chart.js after creation
- Convert/transpose one array into another in JavaScript?
- How to set ChartJS x-axis title