2👍
✅
You will need to use a custom plugin for that:
const customOnClick = {
afterEvent: (chart, evt) => {
const {
event: {
type,
x,
y
}
} = evt;
if (type != 'click')
return;
const {
titleBlock: {
top,
right,
bottom,
left,
}
} = chart
if (left <= x && x <= right && bottom >= y && y >= top)
console.log("in title area")
else
console.log("out of title area")
}
}
var chart = new Chart(document.getElementById('chart').getContext('2d'), {
type: 'bar',
plugins: [customOnClick],
data: {
labels: ['Apples'],
datasets: [{
label: 'Fruit',
backgroundColor: 'teal',
data: [11],
}]
},
options: {
plugins: {
title: {
display: true,
font: {
size: 24,
},
text: ["CLICKING ME IS OF NO USE!", "(Clicking the chart itself works)"],
},
},
onClick: function(area) {
const title = this.titleBlock;
const hitTitle = !!title &&
area.offsetX > title.left && area.offsetX < title.right &&
area.offsetY > title.top && area.offsetY < title.bottom;
document.getElementById('log').innerHTML += hitTitle ? "Title click!!<br>" : "Generic chart click<br>";
}
},
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.1.2"></script>
<canvas id="chart"></canvas>
<div id="log"></div>
Source:stackexchange.com