score:2

Accepted answer

according to events from chart.js documentation, onhover is invoked with the following arguments: the event, an array of active elements (bars, points, etc), and the chart. therefore, your onhover function could be written as follows:

onhover: (e, activeelements, chart) => {
  if (activeelements[0]) {
    let ctx = activeelements[0].element.$context;
    let label = chart.data.labels[ctx.dataindex];
    let value = chart.data.datasets[0].data[ctx.dataindex];
    console.log(label + ': ' + value);
  }
}

please take a look at your amended code below and see how it works.

new chart('tot_pop_chart', {
    type: 'doughnut',
    data: {
      labels: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
      datasets: [{
          data: [1, 2, 3, 4, 5, 6, 7, 8],
          backgroundcolor: ['rgba(200,88,120, 1)',
            'rgba(205,81,54, 1)',
            'rgba(200,134,68, 1)',
            'rgba(153,154,62, 1)',
            'rgba(87,169,91, 1)',
            'rgba(69,178,196, 1)',
            'rgba(114,120,203, 1)',
            'rgba(184,94,188, 1)'
          ],
          borderwidth: 1,
          bordercolor: '#fff3e3'
        }

      ]
    },
    options: {
      animation: {},
      plugins: {
        title: {
          display: true,
          text: "chart",
          font: {
            size: 16
          }
        },
        legend: {
          display: false
        },
        tooltip: {
          enabled: true,
        },
      },
      onhover: (e, activeelements, chart) => {
        if (activeelements[0]) {
          let ctx = activeelements[0].element.$context;
          let label = chart.data.labels[ctx.dataindex];
          let value = chart.data.datasets[0].data[ctx.dataindex];
          console.log(label + ': ' + value);
        }
      }
    }
  }

);
<script src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/3.5.0/chart.min.js"></script>
<canvas id="tot_pop_chart"></canvas>

score:1

from chartjs v2.5 onwards the onhover() parameters have changed. you can access the active element like onhover: (e, activeelements) => {}

onhover: (e, activeelements) => {
   // console.log("hovering1", e);
    
    if (activeelements[0] != undefined){
    console.log(activeelements[0].element.$context);
    // print label and data here
    }
  }

Related Query

More Query from same tag