Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

261
Visualizações
chartjs: doughnut graph onHover get labels and data

I am creating a doughnut graph with chartjs.

I want to create hover effect: print the corresponding data and label when hovering on the chart.

How do I achieve this? This is my current code: https://jsfiddle.net/yigesong1999/dksqag0j/6/

I paste my code below:

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) => {
        console.log("Hovering1", e)
        // print label and data here
      }
    }
  }

);


Really appreciate your help!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

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
    }
  }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda