Chartjs-How to darken other datasets when hovering one dataset in chart js?

0👍

You can define an onHover function as follows:

onHover: (e, activeElements, chart) => {
  const datasets = chart.config.data.datasets;
  if (activeElements[0]) {
    let ctx = activeElements[0].element.$context;
    datasets[ctx.datasetIndex ? 0 : 1].backgroundColor = hoverBgColor;
    datasets[ctx.datasetIndex ? 1 : 0].backgroundColor = bgColor;
  } else {
    datasets.forEach(ds => ds.backgroundColor = bgColor);
  }
  chart.update();
}

For further information, please consult the Chart.js documentation here.

Please take a look at your amended code and see how it works. Note that this sample uses Chart.js v3.8.2, the current most recent version of the library.

const bgColor = ['#8e1212', '#e72323', '#db31a1', '#a931db', '#5d31db', '#3185db', '#31dbc5', '#31db59', '#c5db31', '#db9931', '#e8511c', '#ff7b7b'];
const hoverBgColor = ['#693737', '#ac5e5e', '#a86491', '#9464a8', '#7664a8', '#6486a8', '#64a89f', '#64a874', '#9fa864', '#a88e64', '#ab6e59', '#d7a3a3'];

new Chart('myChart', {
  type: 'doughnut',
  data: {
    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    datasets: [{
        label: 'Fact',
        data: [70, 115, 85, 75, 92, 55, 50, 100, 78, 93, 117, 78],
        backgroundColor: bgColor
      },
      {
        label: 'Plan',
        data: [66, 67, 107, 65, 67, 64, 64, 65, 128, 82, 85, 90],
        backgroundColor: bgColor
      }
    ]
  },
  options: {
    responsive: false,
    onHover: (e, activeElements, chart) => {
      const datasets = chart.config.data.datasets;
      if (activeElements[0]) {
        let ctx = activeElements[0].element.$context;
        datasets[ctx.datasetIndex ? 0 : 1].backgroundColor = hoverBgColor;
        datasets[ctx.datasetIndex ? 1 : 0].backgroundColor = bgColor;
      } else {
        datasets.forEach(ds => ds.backgroundColor = bgColor);
      }
      chart.update();
    },
    plugins: {
      legend: {
        position: "left",
        align: "start",
        fullSize: true,
      }
    },
    hover: {
      mode: 'dataset',
    },
  }
})
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js@3.8.2/dist/chart.min.js"></script>
<div id="hoverval"> </div>
<canvas id="myChart"></canvas>

Leave a comment