0👍
✅
You could use setActiveElements
tooltip/chart API. Here is a snippet code to show how it works.
const ctx = document.getElementById("myChart");
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['January', 'Fabruary', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'user 1 online',
data: [50, 35, 45, 47, 0, 3, 27],
backgroundColor: 'rgba(40, 139, 170, 1)',
borderColor: 'rgb(40, 139, 170)',
pointHoverBackgroundColor: 'yellow',
pointHoverRadius: 20
}]
}
});
document.getElementById('chart').addEventListener('click', function() {
if (myChart.getActiveElements().length > 0) {
myChart.setActiveElements([]);
} else {
myChart.setActiveElements([
{
datasetIndex: 0,
index: 1,
}, {
datasetIndex: 0,
index: 3,
}
]);
}
myChart.update();
});
document.getElementById('tooltip').addEventListener('click', function() {
const tooltip = myChart.tooltip;
if (tooltip.getActiveElements().length > 0) {
tooltip.setActiveElements([], {x: 0, y: 0});
} else {
const chartArea = myChart.chartArea;
tooltip.setActiveElements([
{
datasetIndex: 0,
index: 1
}
],
{
x: (chartArea.left + chartArea.right) / 2,
y: (chartArea.top + chartArea.bottom) / 2,
});
}
myChart.update();
});
.myChartDiv {
max-width: 600px;
max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<html>
<body>
<div class="myChartDiv">
<canvas id="myChart" width="600" height="400"/>
</div>
<button id="chart">Chart active element</button>
<button id="tooltip">Tooltip active element</button>
</body>
</html>
Source:stackexchange.com