I have a bar diagram made with chart.js that's using two datasets and for the labels that looks like this.
<div><canvas id="myChart"></canvas></div>
and the JS for the chart looks like this
const target = [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100];
const realisasi = [0, 0, 0, 0, 0, 10, 0, 10, 1, 0, 0, 0];
const ctx = document.getElementById("myChart").getContext("2d");
const dataset = {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
datasets: [
{ label: "Target", data: target, backgroundColor: "#3d8ef8" },
{ label: "Realisasi", data: testArr, backgroundColor: "#11c46e" },
],
}
const myChart = new Chart(ctx, {
type: 'bar',
data: dataset,
options: {
tooltips: {
callbacks: {
data (t, d) {
const xLabel = d.datasets[t.datasetIndex].label;
const yLabel = t.yLabel >= 1000 ? 'Rp.' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') : '$' + t.yLabel;
return xLabel + ': ' + yLabel;
}
}
},
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
callback: (label, index, labels) => {
return 'Rp.' + label.toFixed(0).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
}
}
]
},
},
});
however the tooltips for the realisasi won't show up when I hover on one of the bar, it only shows the tooltips for the target meanwhile I need to make both tooltips appear when I hover either on the target bar or the realisasi bar. how can I fix that?
You should define options.tooltips.mode: 'index'
according to Chart.js 2.9.4 documentation .
Please take a look at your amended and runnable code below and see how it works.
const target = [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]; const realisasi = [0, 0, 0, 0, 0, 10, 0, 10, 1, 0, 0, 0]; const dataset = { labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], datasets: [{ label: "Target", data: target, backgroundColor: "#3d8ef8" }, { label: "Realisasi", data: realisasi, backgroundColor: "#11c46e" }, ], } new Chart('myChart', { type: 'bar', data: dataset, options: { tooltips: { mode: 'index', callbacks: { data(t, d) { const xLabel = d.datasets[t.datasetIndex].label; const yLabel = t.yLabel >= 1000 ? 'Rp.' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') : '$' + t.yLabel; return xLabel + ': ' + yLabel; } } }, scales: { yAxes: [{ ticks: { beginAtZero: true, callback: (label, index, labels) => { return 'Rp.' + label.toFixed(0).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); } } }] }, }, });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script> <canvas id="myChart" height="90"></canvas>
Also consider to use a newer version of Chart.js, todays most current stable version is
3.8.0
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.