[Chartjs]-Is there a way to highlight a line on a line graph with hover?

2👍

You can use the onHover callback for this in the options:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        backgroundColor: '#FF0000',
        borderColor: '#FF0000'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        backgroundColor: '#0000FF',
        borderColor: '#0000FF'
      },
      {
        label: '# of Cars',
        data: [18, 4, 12, 6, 9, 2],
        backgroundColor: '#FF1493',
        borderColor: '#FF1493'
      }
    ]
  },
  options: {
    onHover: (e, activeEls, chart) => {
      if (activeEls.length === 0) {
        chart.data.datasets.forEach((dataset) => {
          dataset.backgroundColor = dataset.backgroundColor.length === 9 ? dataset.backgroundColor.slice(0, -2) : dataset.backgroundColor;
          dataset.borderColor = dataset.borderColor.length === 9 ? dataset.borderColor.slice(0, -2) : dataset.borderColor;
        });
        chart.update();
        return;
      }

      const hoveredEl = chart.getElementsAtEventForMode(e, 'point', {
        intersect: true
      }, true)[0]

      chart.data.datasets.forEach((dataset, i) => {
        dataset.backgroundColor = (hoveredEl.datasetIndex === i || dataset.backgroundColor.length === 9) ? dataset.backgroundColor : dataset.backgroundColor + '4D';
        dataset.borderColor = (hoveredEl.datasetIndex === i || dataset.borderColor.length === 9) ? dataset.borderColor : dataset.borderColor + '4D';
      });

      chart.update();
    },
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.0/chart.js"></script>
</body>

Leave a comment