[Chartjs]-Change point color on click using ChartJS

9👍

The following approach makes use of:

  • the pointBackgroundColor dataset property, an array which will hold the current colors of points. When a point is clicked, the associated array value will be changed to white and the chart will be updated.
  • the onClick chart option, a function that is “called if the event is of type ‘mouseup’ or ‘click’.” It is “called in the context of the chart and passed the event and an array of active elements.”

More at the docs.

Long story code:

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [72, 49, 43, 49, 35, 82],
      pointBackgroundColor: ["red", "blue", "yellow", "green", "purple", "orange"]
    }]
  },
  options: {
    onClick: function(evt, activeElements) {
      var elementIndex = activeElements[0]._index;
      this.data.datasets[0].pointBackgroundColor[elementIndex] = 'white';
      this.update();
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

And a fiddle to play with.

0👍

Update accepted answer for V3, also made it more flexible by not using a hardcoded datasetIndex.

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [72, 49, 43, 49, 35, 82],
        pointBackgroundColor: ["red", "blue", "yellow", "green", "purple", "orange"]
      },
      {
        label: '# of Points',
        data: [62, 59, 33, 39, 25, 62],
        pointBackgroundColor: ["red", "blue", "yellow", "green", "purple", "orange"]
      }
    ]
  },
  options: {
    onClick: (evt, activeElements) => {
      if (activeElements.length === 0) {
        return;
      }

      const chart = evt.chart;
      const elementIndex = activeElements[0].index;
      const datasetIndex = activeElements[0].datasetIndex;

      chart.data.datasets[datasetIndex].pointBackgroundColor[elementIndex] = 'white';
      chart.update();
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

Leave a comment