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

17👍

With Chart.js 3.x:

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

With Chart.js 2.x:

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

5👍

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';
 }

3👍

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';
        }
      }
    }
  }
}

0👍

This is almost 5 years old question, using the version 3.x.x of ChartJS we just need to declare some event handlers like onHover, onClick and define the events handle by the tooltip like events: ['click'].

Here we have a working snippet:

const isArray = a => a instanceof Array
const isNull = a => a == null
const cursor = a => {
  if (isNull(a)) return 'default'
  if (!isArray(a)) return 'pointer'
  if (isArray(a) && a.length > 0) return 'pointer'

  return 'default'
}

const $canvas = document.getElementById('chart')
const onHover = (e, item) => {
  $canvas.style.cursor = cursor(item)
}
const onLeave = () => {
  $canvas.style.cursor = 'default'
}

const onClick = (event, items) => {
  if (items.length === 0) return

  console.log('onclick')
}

const lineChart = new Chart($canvas, {
  type: 'bar',
  data: {
    labels: ['May', 'June', 'July'],
    datasets: [{
      data: [15, 25, 15],
      label: "My Dataset1",
      backgroundColor: "#00F",
      fill: false
    }, {
      data: [35, 15, 25],
      label: "My Dataset2",
      backgroundColor: "#F00",
      fill: false
    }]
  },
  options: {
    responsive: true,
    onHover,
    onClick,
    plugins: {
      tooltip: {
        // Tooltip will only receive click events
        events: ['click'],
      },
      legend: {
        onHover,
        onLeave,
      },
    },
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<canvas id="chart" width="600" height="180"></canvas>

Leave a comment