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

210
Visualizações
How can I highlight a bar in ChartJS when selected in the legend?

I need to change background color of bar when selected it in the legend. When I updated chart with ci.update() color is reset.

options: {
        plugins: {
            legend: {
                display: true,
                position: 'right',
                onClick: function (e, legendItem, legend) {
                    const index = legendItem.datasetIndex;
                    const ci = legend.chart;
                    const meta = ci.getDatasetMeta(index);
                    const element = meta.data[0];


                    if (!legendItem.checked) {
                        element.options.backgroundColor = 'rgba(255, 159, 64, 1)';
                        legendItem.lineWidth = 2;
                        legendItem.strokeStyle = 'rgba(0,0,0, 1)';
                        legendItem.checked = true;
                    } else {
                        legendItem.checked = false;
                    }

                    ci.update();
                }
            }
        }
    }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When the chart.update() is invoked, the chart is re-configuring itself starting from chart.data.datasets and all element options (changed in the meanwhile) are lost. The chart.data.datasets must be changed. The original backgroundColors must be stored because otherwise they will be lost.

const ctx = document.getElementById("myChart");
const backgroundColors = ['rgba(40, 139, 170, 1)', 'rgba(40, 139, 0, 1)'];
const myChart = new Chart(ctx, {
      type: 'bar',
    data: {
        labels: ['January', 'Fabruary', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'user 1 online',
            data: [50, 35, 45, 47, 10, 3, 27],
            backgroundColor: backgroundColors[0],
            borderWidth: 0,
            borderSkipped: 'start'
        },
        {
            label: 'user 2 online',
            data: [50, 35, 45, 47, 10, 3, 27],
            backgroundColor: backgroundColors[1],
            borderWidth: 0,
            borderSkipped: 'start'
        }]
    },
    options: {
      plugins: {
        legend: {
          display: true,
          position: 'right',
          onClick: function (e, legendItem, legend) {
            const index = legendItem.datasetIndex;
            const ci = legend.chart;
            const dataset = ci.data.datasets[index];
            if (!dataset.checked) {
              dataset.backgroundColor = 'rgba(255, 159, 64, 1)';
              dataset.borderWidth = 2;
              dataset.borderColor = 'rgba(0,0,0, 1)';
              dataset.checked = true;
            } else {
              dataset.backgroundColor = backgroundColors[index]; 
              dataset.borderWidth = 0;
              dataset.borderColor = null;
              dataset.checked = false;
            }
            ci.update();
          }
        }
      }
    }
 });
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<html>
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600" height="400"/>
    </div>
  </body>
</html>

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