ChartJS doughnut data toggle on custom button click

Solution 1:

The toggle function could be written as follows:

function toggleData(button, category) {
  chart.toggleDataVisibility(category);
  chart.update();
  if (chart.getDataVisibility(category)) {
    button.classList.remove('hidden');
  } else {
    button.classList.add('hidden');
  }
}

Further information about the Chart.js API can be found here.

Please take a look at your amended code and see how it works:

const chart = new Chart('chart', {
  type: 'doughnut',
  data: {
    labels: ['Cat1', 'Cat2', 'Cat3', 'Cat4'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5],
      backgroundColor: [
        'rgb(143,219,226)',
        'rgb(255,206,148)',
        'rgb(158,239,181)',
        'rgb(251,172,172)'
      ],
      borderColor: [
        'rgb(143,219,226)',
        'rgb(255,206,148)',
        'rgb(158,239,181)',
        'rgb(251,172,172)'
      ],
      borderWidth: 1,
    }]
  },
  options: {
    responsive: false,
    plugins: {
      legend: {
        display: false
      }
    }
  }
});

function toggleData(button, category) {
  chart.toggleDataVisibility(category);
  chart.update();
  if (chart.getDataVisibility(category)) {
    button.classList.remove('hidden');
  } else {
    button.classList.add('hidden');
  }
}
.hidden {
  text-decoration: line-through;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
<div style="display: flex; flex-direction: column; align-items: center;">
  <div style="display: flex; gap: 10px; margin-bottom: 10px">
    <button id="category0" onclick="toggleData(this, 0)">category0</button>
    <button id="category1" onclick="toggleData(this, 1)">category1</button>
    <button id="category2" onclick="toggleData(this, 2)">category2</button>
    <button id="category3" onclick="toggleData(this, 3)">category3</button>
  </div>
  <canvas id="chart" width="200"></canvas>
</div>