I am working with chartJS bar graph. I want to detect the location of click. How can I detect if graph was clicked in bar or outside the bar region in chartJS?
const waterFChart = new Chart(canvasRef.current, {
plugins: [ChartDataLabels],
type: "bar",
data: {
labels: ["Label 1", "Label 2", "Label 3", "Label 4", "Label 5"],
datasets: [
{
label: 'Failures',
type: "bar",
data: [10, 20, 30, 41, 51],
backgroundColor:"green",
hoverBackgroundColor: darkBar,
}
]
}
options:{
onClick: function (e) {
if(clicked on bar){
{alert("Clicked on bar")
}
else {
alert("Clicked outside of the bar");
}
},
);
You get an array containing all the active elements as second argument so if this array has a length of 0 no bar has been clicked and if it has a length greater then 0 a bar has been clicked:
options: {
onClick: function (evt, activeEls) {
if (activeEls.length === 0) {
alert("clicked outside of bar");
} else {
alert("clicked on bar");
}
}
}