Chartjs-Refresh chart.js dataset background colors

1👍

This is because you dont actually update anything, you will also need to update the colors before calling the update function:

const labels = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
];

const getBackgroundColors = () => ([
  getComputedStyle(document.documentElement).getPropertyValue('--color1').trim(),
  getComputedStyle(document.documentElement).getPropertyValue('--color2').trim(),
  getComputedStyle(document.documentElement).getPropertyValue('--color3').trim()
])

const data = {
  labels: labels,
  datasets: [{
    label: 'My First dataset',
    data: [29, 45, 26],
    backgroundColor: getBackgroundColors()
  }]
};

const config = {
  type: 'bar',
  data: data
};

const myChart = new Chart(
  document.getElementById('myChart'),
  config
);


window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
  myChart.data.datasets[0].backgroundColor = getBackgroundColors();
  myChart.update();
  alert('switched');
});
:root {
  --color1: red;
  --color2: green;
  --color3: blue;
}

@media (prefers-color-scheme: dark) {
  body {
    background-color: #222;
  }
   :root {
    --color1: yellow;
    --color2: purple;
    --color3: pink;
  }
}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<div>
  <canvas id="myChart"></canvas>
</div>

Leave a comment