[Chartjs]-JavaScript function based on counter

1👍

This is because you have a singel global toggle. If you instead make an object where you track each element of they have been clicked and thus expanded you wont have this behaviour:

const enlarged = {};
const expandAmount = 10;

const options = {
  type: 'pie',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
    }]
  },
  options: {
    onClick: (evt, activeEls, chart) => {
      const key = `${activeEls[0].datasetIndex}${activeEls[0].index}`;

      if (enlarged[key] || enlarged[key] === undefined) {
        activeEls[0].element.outerRadius += expandAmount;
        enlarged[key] = false;
      } else {
        activeEls[0].element.outerRadius -= expandAmount;
        enlarged[key] = true;
      }
    }
  }
}

const 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.6.1/chart.js"></script>
</body>

EDIT:

Update with desired behaviour, keep a global variable that keeps track of the current dataset and data index, if set first set that back and then enlarge the current slice, if key is same as old key dont do anything

let enlarged = '';
const expandAmount = 10;

const options = {
  type: 'pie',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
    }]
  },
  options: {
    onClick: (evt, activeEls, chart) => {
      const key = `${activeEls[0].datasetIndex}-${activeEls[0].index}`;
      const keys = enlarged.split('-');

      if (keys.length == 2) {
        chart.getDatasetMeta(keys[0]).data[keys[1]].outerRadius -= expandAmount
      }

      if (key !== enlarged) {
        activeEls[0].element.outerRadius += expandAmount;
        enlarged = key;
      } else {
        enlarged = ''
      }
    }
  }
}

const 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.6.1/chart.js"></script>
</body>

Leave a comment