score:7
Change this line
document.getElementById('roomForChart').innerHTML += htmlForGraph;
to this
holder = document.getElementById('roomForChart');
holder.innerHTML += htmlForGraph;
and further you'll have your snippet, modified a bit
holder.onclick = function(evt){
var activePoints = myLineChart.getPointsAtEvent(evt);
// => activePoints is an array of points on the canvas that are at the same position as the click event.
alert("See me?");
};
Add console.log(activePoints);
within onclick handler to see the content of the activePoints
variable. As I can see, there are three objects. For instance these are values for activePoints[0]
datasetLabel: "Usage Plan"
fillColor: "rgba(244,0,0,1)"
highlightFill: "#fff"
highlightStroke: "rgba(220,220,220,1)"
label: "Aug 4"
strokeColor: "#fff"
value: 1024
x: 371
y: 12.356097560975627
And they may be accessed as following
activePoints[0].label
activePoints[0].x
activePoints[0].y
activePoints[0].value
It will be good to check if the property is undefined
first, since there are no data behind every click event.
score:1
V3
You can also use the build in onClick
option which gets the following paramters: (event, activeElements, chartInstance)
So you can just read the array you get as second element to see which elements have been active. By default this array contains only 1 item but if you change your interaction modes multiple items could be in here.
var options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
backgroundColor: 'orange'
}
]
},
options: {
onClick: (evt, activeElements, chart) => {
console.log(`DatasetIndex: ${activeElements[0].datasetIndex} DataIndex: ${activeElements[0].index}`)
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>
In v3 the getElementsAtEvent
has been removed and now you have to use: chart.getElementsAtEventForMode(event, 'index', { intersect: true }, false)
If you want to use getDatasetAtEvent
you now have to use: chart.getElementsAtEventForMode(e, 'dataset', { intersect: true }, false)
score:5
The answers provided to date are close to the correct solution(s), but are incomplete. You need to use the getElementsAtEvent() to get the correct elements, but this gives you a collection of elements that are at the clicked x-index. In the even that you are using more than one dataset, this could be several values, one from each data set.
To figure out the correct data set to pull from, call the getDatasetAtEvent() method. This will return a list of the elements that contains the clicked dataset element. Pick the dataset Id from any of them, they are all the same Id.
Put the two together and you have the call you need to figure out the data contained in the clicked element. Passing in more than just and x and y value when you init your data set will let you do all sorts of neat tricks with this event. (For example, trigger a popup with more detailed info about the event)
There might be a more succinct way of getting this data, but I didn't find it mucking around the chart docs and tickets. Perhaps they will add it in a future release.
// chart_name is whatever your chart object is named. here I am using a
// jquery selector to attach the click event.
$('#' + chart_name).click(function (e)
{
var activePoints = myChart.getElementsAtEvent(event);
var activeDataSet = myChart.getDatasetAtEvent(event);
if (activePoints.length > 0)
{
var clickedDatasetIndex = activeDataSet[0]._datasetIndex;
var clickedElementIndex = activePoints[0]._index;
var value = myChart.data.datasets[clickedDatasetIndex].data[clickedElementIndex];
}
// todo: add code to do something with value.
});
score:6
I couldn't get the onclick
method to work.
But I finally managed to run it using the click
method:
$("#canvas_id").click(function(e) {
var activeBars = myBarChart.getBarsAtEvent(e);
console.log(activeBars[0]);
});
Note: this example if for the Bar chart - other charts have slightly different methods to retrieve the points (see the documentation).
score:8
if youre using the new ChartJs version use this:
canvas.onclick = function(evt){
var activePoints = myLineChart.getElementsAtEvent(evt);
};
Source: stackoverflow.com
Related Query
- How to add an on click event to my Line chart using Chart.js
- How to add on click event to chart js
- How to add vertical line in bar chart using chartJs and ng2-charts?
- How to add text inside the doughnut chart using Chart.js?
- How to add second Y-axis for Bar and Line chart in Chart.js?
- How to add text in centre of the doughnut chart using Chart.js?
- How to add gradient background to Line Chart [vue-chart.js]
- Click event of stacked line chart not working
- Using chart js version 3, how to add custom data to external tooltip?
- How to add area with break on line chart with fill color
- Add data to line chart using chart.js
- How to make aspecific API call from within a Line Chart class in ReactJS using react-chartjs-2?
- how to add percentage value to legend field in pie chart using chart.js
- How to sort XY line chart tooltip items based on value and add thousands separators?
- How can I add a euro sign (€) to all tooltips in my chart js line chart
- How to add text inside the doughnut chart using Chart.js version 3.2.1
- How to add new dataset in line chart of chart.js by iterating over dictionary in JavaScript?
- How to add an end line to my graph using Chart.js?
- How do you set x and y axis and Title for a line chart using charts.js?
- How to add text inside the doughnut chart using Chart.js AngularJS 2.0?
- Chart js how to toggle line without click
- How to add data dynamically to primevue Line chart from vuejs3?
- How to add image inside the doughnut chart using chart.js?
- How to plot a line chart which has both the start and points outside the canvas area using Chart.js
- How to draw multiple color bars in a bar chart along a Horizontal Line using chart.js
- How to decrease bottom width of triangle using line chart in chartJs?
- How to Draw a line on chart without a plot point using chart.js
- How to edit my custom tooltips in my line chart using chart.js?
- How to compute x,y values from a click event using x,y pixel coordinates in ChartJS?
- How to create a line on a chart using chartjs-plugin-annotation
More Query from same tag
- How to use output of JSON.parse() as a input of HTML charts' data field?
- How to create Chart with 2 variables (x,,y)
- How to navigate tooltips popup by clicking custom buttons outside Chart.js v2 canvas?
- TypeError: CanvasRenderService is not a constructor
- Getting (X,Y) point on mouse click on chart
- Chartjs with Node.js : Unexpected token <
- ChartJS : It's not showing in html on Django
- Line ChartJS empty / null values doesn't break the line
- (scaled) y value for given x value
- Chart.js pie tooltip getting cut
- can't set ChartJS canvas width
- Chart.js only appears randomly, and disappears on page refresh
- How to Create a Custom Logarithmic Axis in Chart.js
- Full size download Chartjs canvas on mobile device
- call Column that is complex in query
- ChartJS separate charts per JSON object, and not when hovered over
- Trying to refresh label when click on it. Cannot read property '_meta' of undefined"
- How can we build charts on Polymer 1.0 using Chart.js?
- Delay animation of chart.js
- Chart.js data values from textbox input only load once
- How can I have different values for the chart and the tooltip in chart.js?
- API data not loading in chart.js until element is inspected or page is resized
- How to position chart details next to a chart responsive for multiple devices?
- event click only x-axis label chartJS
- Line chart with combination of fill and line
- Chartjs: display value in html element when hovering a bar
- Chartjs Line Color Between Two Points
- Fully destroy charts on ngDestroy method from Angular 4
- ChartJS - Returning labels and data from server on different calls
- Convert FirestoreCollection into an array?