We are using Chart.js (version 2.6.0) for a bar chart in an Angular 5 application and the client wanted us to disable hover events for chart interactions(they only wanted the bar to change and the tooltips to show up when the user clicked on a bar).
in the bar chart options object, we have the following defined for the events property:
events: ["touchstart","touchmove","click"]
That disables hovering events over the bar chart. Now however, the client wants us to change the cursor to a pointer when the user hovers over one of the bars, so that they know they can click on it, which is a valid point. I've found several solutions here on SO, but I can't seem to find a way to do it without adding "mousemove" to the events property, which just enables hovering interactions on the entire chart.
What really confuses me is that options.hover has an event property called "onHover" that has a callback, but it fires when ANY of the defined events happens, including clicks.
http://www.chartjs.org/docs/latest/general/interactions/events.html
Is this even possible without re-enabling the hover interaction in general? Any help would be greatly appreciated.
Not sure if it applies to your case, but with Chart.js 2.x I use this approach, which does not use the options.hover
property. Just add this in the options:
onHover: (event, chartElement) => {
event.target.style.cursor = chartElement[0] ? 'pointer' : 'default';
}
Hope it helps.
Based on @Luca Fagioli answer, in my case, I didn't want to disable the click events in my chart so i added:
events: ['mousemove', 'click'],
onHover: (event, chartElement) => {
event.target.style.cursor = chartElement[0] ? 'pointer' : 'default';
}
now that you have a cursor on the chart you want the cursor in the legend too - if they are clickable - so in the legend settings toy hold add:
onHover: (event) => {
event.target.style.cursor = 'pointer';
}
For versions > 3.x you find the target under native
options: {
plugins : {
legend: {
labels: {
onHover: function (e) {
e.native.target.style.cursor = 'pointer';
},
onLeave: function (e) {
e.native.target.style.cursor = 'default';
}
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With