I am creating a doughnut graph with chartjs.
I want to create hover effect: print the corresponding data and label when hovering on the chart.
How do I achieve this? This is my current code: https://jsfiddle.net/yigesong1999/dksqag0j/6/
I paste my code below:
new Chart('tot_pop_chart', {
type: 'doughnut',
data: {
labels: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
datasets: [{
data: [1,2,3,4,5,6,7,8],
backgroundColor: ['rgba(200,88,120, 1)',
'rgba(205,81,54, 1)',
'rgba(200,134,68, 1)',
'rgba(153,154,62, 1)',
'rgba(87,169,91, 1)',
'rgba(69,178,196, 1)',
'rgba(114,120,203, 1)',
'rgba(184,94,188, 1)'
],
borderWidth: 1,
borderColor: '#fff3e3'
}
]
},
options: {
animation: {},
plugins: {
title: {
display: true,
text: "Chart",
font: {
size: 16
}
},
legend: {
display: false
},
tooltip: {
enabled: true,
},
},
onHover: (e) => {
console.log("Hovering1", e)
// print label and data here
}
}
}
);
Really appreciate your help!
According to Events from Chart.js documentation, onHover is invoked with the following arguments: The event, an array of active elements (bars, points, etc), and the chart. Therefore, your onHover function could be written as follows:
onHover: (e, activeElements, chart) => {
if (activeElements[0]) {
let ctx = activeElements[0].element.$context;
let label = chart.data.labels[ctx.dataIndex];
let value = chart.data.datasets[0].data[ctx.dataIndex];
console.log(label + ': ' + value);
}
}
Please take a look at your amended code below and see how it works.
new Chart('tot_pop_chart', {
type: 'doughnut',
data: {
labels: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
datasets: [{
data: [1, 2, 3, 4, 5, 6, 7, 8],
backgroundColor: ['rgba(200,88,120, 1)',
'rgba(205,81,54, 1)',
'rgba(200,134,68, 1)',
'rgba(153,154,62, 1)',
'rgba(87,169,91, 1)',
'rgba(69,178,196, 1)',
'rgba(114,120,203, 1)',
'rgba(184,94,188, 1)'
],
borderWidth: 1,
borderColor: '#fff3e3'
}
]
},
options: {
animation: {},
plugins: {
title: {
display: true,
text: "Chart",
font: {
size: 16
}
},
legend: {
display: false
},
tooltip: {
enabled: true,
},
},
onHover: (e, activeElements, chart) => {
if (activeElements[0]) {
let ctx = activeElements[0].element.$context;
let label = chart.data.labels[ctx.dataIndex];
let value = chart.data.datasets[0].data[ctx.dataIndex];
console.log(label + ': ' + value);
}
}
}
}
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.min.js"></script>
<canvas id="tot_pop_chart"></canvas>
From ChartJS v2.5 onwards the onHover() parameters have changed.
You can access the active element like onHover: (e, activeElements) => {}
onHover: (e, activeElements) => {
// console.log("Hovering1", e);
if (activeElements[0] != undefined){
console.log(activeElements[0].element.$context);
// print label and data here
}
}