Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing cursor to pointer on Chart.js bar chart when hover (mousemove) event is disabled?

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.

like image 916
budkin Avatar asked Mar 01 '18 00:03

budkin


3 Answers

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.

like image 50
Luca Fagioli Avatar answered Oct 26 '22 11:10

Luca Fagioli


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';
 }
like image 37
Erez Lieberman Avatar answered Oct 26 '22 13:10

Erez Lieberman


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';
        }
      }
    }
  }
}
like image 27
Daniele Rugginenti Avatar answered Oct 26 '22 13:10

Daniele Rugginenti