I would like to display the value to the corresponding bar when hovering over it inside and html tag. Once hovering over the value should be displayed inside the "valueHeader" html element. Can someone give a tip or guidance on how to achieve this.
new Chart('myChart', {
data: {
labels: ['A', 'B', 'C', 'D', 'E'],
datasets: [{
label: 'X',
type: 'bar',
backgroundColor: 'rgb(0, 0, 255)',
data: [2, 3, 15, 34, 0],
barThickness: 40
}
]
},
options: {
plugins: {
legend: {
display: false
},
},
scales: {
y: {
beginAtZero: true
},
x: {
stacked: true,
grid: {
display: false
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<p>Today you have worked out for this amount of minutes: </p> <p id="valueHeader"> </p>
<canvas id="myChart" height="100"></canvas>
You need to add a hover event:
options: {
onHover: (event, active, chart) => {
if (active.length) {
let first = active[0];
let setIndex = first.datasetIndex;
let index = first.index;
let data = chart.data.datasets[setIndex].data[index];
let str = "X: " + data.x + ", Y: " + data.y;
let header = document.getElementById("valueHeader");
header.innerHTML = str;
}
},
Here is a JSFiddle if you want to see it in action.