0👍
✅
You could let you ChartJS listen to the mouseOut
event.
https://www.chartjs.org/docs/latest/configuration/interactions.html#event-option
Then use a custom plugin to catch that event and remove the lines:
plugins: [{
id: 'someEventCatcher',
beforeEvent(chart, args, pluginOptions) {
if (args.event.type === 'mouseout') {
chart.options.scales.x.grid.color = new Array(5).fill('transparent');
chart.update();
}
}
}],
I’ve also added the following to the onHover
function:
if (!chartElement.length) {
return;
}
This will prevent chartElement[0].index;
from failing if there is nothing you’re hovering over
Small demo based on your codepen
const chartCanvas = document.getElementById('chart-canvas');
const chart = new Chart(chartCanvas, {
type: 'line',
data: {
labels: ['December 2022','January 2023','February 2023','March 2023','Aprile 2023'],
datasets: [
{
label: 'Label 1',
data: [10020, 4120, 63510, 13220, 11225],
borderWidth: 1,
borderColor: '#C6AB8D',
backgroundColor: '#C6AB8D',
pointRadius: 0,
pointHoverRadius: 6,
},
{
label: 'Label 2',
data: [9020, 325, 6512, 7220, 4220],
borderWidth: 1,
borderColor: '#ffffff',
backgroundColor: '#ffffff',
pointRadius: 0,
pointHoverRadius: 6,
}
]
},
plugins: [{
id: 'someEventCatcher',
beforeEvent(chart, args, pluginOptions) {
if (args.event.type === 'mouseout') {
chart.options.scales.x.grid.color = new Array(5).fill('transparent');
chart.update();
}
}
}],
options: {
events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
responsive: true,
maintainAspectRatio: false,
interaction: {
mode: 'index',
intersect: false,
},
scales: {
x: {
offset: true,
border: {
color: 'rgba(255, 245, 236, 0.4)',
dash: [4,4]
},
grid: {
color: 'transparent',
},
ticks: {
color: 'rgba(255, 245, 236, 0.4)',
}
},
y: {
beginAtZero: true,
border: {
color: 'rgba(255, 245, 236, 0.4)',
},
grid: {
color: 'rgba(255, 245, 236, 0.1)',
},
ticks: {
color: 'rgba(255, 245, 236, 0.4)',
}
}
},
onHover: (event, chartElement) => {
if (!chartElement.length) {
return;
}
const index = chartElement[0].index;
const totalCount = chart.data.labels.length;
const gridColors = [];
for (let i = 0; i < totalCount; i++) {
if (i == index) {
gridColors.push('rgba(255, 245, 236, 0.4)');
} else {
gridColors.push('transparent');
}
}
chart.options.scales.x.grid.color = gridColors;
chart.update();
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div style="background: rgba(0, 23, 47, 1);">
<canvas id="chart-canvas" height="600"></canvas>
</div>
Source:stackexchange.com