chartjs-plugin-crosshair
chartjs-plugin-crosshair copied to clipboard
Hide crosshair on mouseout event
I don't believe this exists as an option, so this may be a feature request. My goal is to hide the crosshair on something like a mouseout event from the chart.
By default the crosshair remains in position one the cursor has left the chart's bounds. Here's a screenshot the crosshairs present on multiple charts on the page (the graph vertical grey lines).
FWIW I did notice that the crosshair disappears for a specific chart if it is inspected with the developers tools, so I'd be curious what mechanism/event is responsible for that. Thanks!
OK this line of code seems relevant.
So that chart.crosshair.enabled
flag works correctly, but the crosshair shows even when it is false
. That would sense if sync
is also enabled (as it wouldn't work otherwise), but if not I would expect the crosshair to hide itself when chart.crosshair.enabled
is false
.
Hmm, so this line early returns and the crosshair becomes hidden if the mouse leaves the chart through the left or right border (moving along the x-axis); however, when the mouse leaves via the top or bottom border (moving along the y-axis) the afterDraw
function is not executed so that line does not get hit. There might be a race condition going on between setting the enabled
value and the event firing where it is respected.
My solution was to add a very small plugin to chartjs which handles "afterEvent > mouseout" and updates the chart:
const CrosshairRemover = {
id: 'crosshair-remover',
afterEvent: (chart, args, options) => {
if(args.event.type == 'mouseout') {
chart.update('none')
}
}
}
Perhaps that helps you too...
<Chart
{...}
ref={chartRef}
onMouseOut={() => {
chartRef.current.crosshair.enabled = false;
chartRef.current.crosshair.reset();
}}
/>
This worked for me as well.