Chart.js how to show cursor pointer for labels & legends in line chart

ChartJs 2 provides onHover and onLeave handlers. We can use them to change the cursor:

  legend: {
    display: true,
    onHover: function (e) {
      e.target.style.cursor = 'pointer'
    },
    onLeave: function (e) {
      e.target.style.cursor = 'default'
    }
  }

Better Approach

no need of jQuery to select canvas element (line-chart).

1 ▸ Solution :

add the following in your chart options :

   legend: {
      onHover: function(e) {
         e.target.style.cursor = 'pointer';
      }
   },
   hover: {
      onHover: function(e) {
         var point = this.getElementAtEvent(e);
         if (point.length) e.target.style.cursor = 'pointer';
         else e.target.style.cursor = 'default';
      }
   }

2 ▸ Solution :

set tooltip­'s mode to dataset :

tooltips: {
   mode: 'dataset'
}

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

var line_chart = new Chart(document.getElementById("line-chart"), {
   type: 'line',
   data: {
      labels: ['May', 'June', 'July'],
      datasets: [{
         data: [15, 25, 15],
         label: "My Dataset1",
         borderColor: "#00F",
         fill: false
      }, {
         data: [35, 15, 25],
         label: "My Dataset2",
         borderColor: "#F00",
         fill: false
      }]
   },
   options: {
      tooltips: {
         mode: 'dataset',
      },
      legend: {
         onHover: function(e) {
            e.target.style.cursor = 'pointer';
         }
      },
      hover: {
         onHover: function(e) {
            var point = this.getElementAtEvent(e);
            if (point.length) e.target.style.cursor = 'pointer';
            else e.target.style.cursor = 'default';
         }
      }
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>

<div style='width:80%'>
   <canvas id="line-chart" width="800" height="450"></canvas>
</div>

Just add this to the options:

onHover: (event, chartElement) => {
    const target = event.native ? event.native.target : event.target;
    target.style.cursor = chartElement[0] ? 'pointer' : 'default';
}

  • As of Chart js version 3.5.1 the onHover() option looks slightly different and the method to find the points has changed as well.

  • 'target' is nested one more level under 'e.native'

  • By setting interaction mode to 'index' I'm able to see my combined chart values in the one tooltip on hover.

    options: {
       interaction: { mode: 'index' },
       onHover: function (e) {
         const points = this.getElementsAtEventForMode(
           e,
           'index', { axis: 'x', intersect: true },
           false
         );
    
         if (points.length) e.native.target.style.cursor = 'pointer';
         else e.native.target.style.cursor = 'default';
       }
    }
    

Cursor Pointer & Combined Tooltip