Chartjs-On hover / click change background color for the same bar on multiple charts โ€“ chart.js

0๐Ÿ‘

โœ…

You need to assign the second chart to a constant or a variable when your create it.

const myChart2 = new Chart('myChart2', { ... }

Then you can access it from within the onClick handler and perform almost the same operations as you did for the first chart.

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

new Chart('myChart1', {
  type: 'bar',
  data: {
    labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: ["blue", "blue", "blue", "blue", "blue", "blue"],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      y: {
        beginAtZero: true
      }
    },
    onClick: function(evt, activeElements, chart) {
      const elementIndex = activeElements[0].index;
      const label = chart.data.labels[elementIndex];
      const bgColor = chart.data.datasets[0].backgroundColor[elementIndex];
      const newBgColor = bgColor === 'red' ? 'blue' : 'red';
      this.data.datasets[0].backgroundColor[elementIndex] = newBgColor;
      this.update();      
      
      const iLabelChart2 = myChart2.data.labels.indexOf(label);
      if (iLabelChart2 !== undefined) {
        myChart2.data.datasets[0].backgroundColor[iLabelChart2] = newBgColor;
        myChart2.update();
      }
    }
  }
});

const myChart2 = new Chart('myChart2', {
  type: 'bar',
  data: {
    labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
    datasets: [{
      label: '# of Votes',
      data: [8, 4, 4, 4, 4, 4],
      backgroundColor: ["blue", "blue", "blue", "blue", "blue", "blue"],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      y: {
        beginAtZero: true
      }
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@^4"></script>
<div style="width: 400px;">
  <canvas id="myChart1"></canvas>
  <canvas id="myChart2"></canvas>
</div>

Leave a comment