Chartjs-(chart.js v3.5.1) change bar background, label font color on click

0👍

The key point is to address the correct properties in the chart configuration when changing the data. These are basically chart.data.datasets[0]backgroundColor, chart.options.scales.x.ticks.color and chart.options.scales.x.ticks.font.weight.

Please take a look at your amended code below and see how it could work.

new Chart("barChart", {
  type: 'bar',
  data: {
    labels: ["jan", "fab", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"],
    datasets: [{
      label: 'Data',
      data: [8, 2, 3, 0, 5, 2, 2, 0, 0, 6, 10, 2],
      backgroundColor: 'rgb(197,197,197)',
      borderRadius: 6,
      borderSkipped: false,
      barThickness: 20
    }]
  },
  options: {
    onClick: (event, elements, chart) => {
      if (elements.length) {
        const dataset = chart.data.datasets[0];
        dataset.backgroundColor = [];
        const ticks = chart.options.scales.x.ticks;
        ticks.color = [];
        ticks.font.weight = [];
        const i = elements[0].index;
        for (let i = 0; i < dataset.data.length; i++) {
          if (elements[0].index == i) {
            dataset.backgroundColor[i] = 'rgb(32,32,32)';
            ticks.color[i] = 'rgb(32,32,32)';
            ticks.font.weight[i] = 600;
          } else {
            dataset.backgroundColor[i] = 'rgb(197,197,197)';
            ticks.color[i] = 'rgb(153,153,153)';
            ticks.font.weight[i] = 400;
          }
        }
        chart.update();
      }
    },
    scales: {
      y: {
        display: false
      },
      x: {
        grid: {
          color: 'white',
          drawBorder: false
        },
        ticks: {
          color: 'rgb(153,153,153)',
          font: {
            family: "'Pretendard', sans-serif",
            weight: 400
          }
        }
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="barChart"></canvas>

0👍

The above solution guided me to my answer. But for some reason I was not able to update the weight by simply updating the ticks property and updating the chart. I am on chartjs 3.9.1 and the solution that worked for me was to use the scriptable options. I still had to ensure that I called ‘chart.update()’ from the onClick event.

I stored the index in a const variable which I then accessed under the chartOptions to set the weight:

ticks: {
          autoSkip: false,
          font: {
                   size: 12,
                   weight: (w) => {
                            if (highlighted.includes(w.index)) {
                                return 700;
                            } else {
                                return 100;
                            }
                    }
                }
            }

Hope this helps.

Leave a comment