5👍
✅
You can loop through chart instances dynamically using the Chart.instances
object. For example:
Chart.helpers.each(Chart.instances, function(instance){
instance.chart.update();
});
I’ve modified your example below to update all charts in the toggle function. You’ll notice that the font color now changes with toggle.
// set function for theme
function changeTheme(darkTheme = false) {
if (darkTheme) {
document.body.classList.add('dark-theme');
Chart.defaults.global.defaultFontColor = 'white';
} else {
document.body.classList.remove('dark-theme');
Chart.defaults.global.defaultFontColor = 'black';
}
// Force updates to all charts
Chart.helpers.each(Chart.instances, function(instance){
instance.chart.update();
});
}
changeTheme(false);
// button to toggle theme
let darkThemeActive = false;
document.getElementById('toggleDarkTheme').addEventListener('click', ()=>{
darkThemeActive = !darkThemeActive;
changeTheme(darkThemeActive);
});
/* example chart, pretend like you dont have access to this scope ;) */
{
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: true
}
});
}
button {
background-color: #eee;
color: rgba(0,0,0,0.87);
border: none;
border-radius: 3px;
padding: 0.5rem;
}
.dark-theme {
background-color: #212121;
color: white;
}
.dark-theme button {
background-color: #212121;
color: white;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script>
<div>
<button id="toggleDarkTheme">toggleDarkTheme</button>
</div>
<canvas id="myChart" width="400" height="400"></canvas>
Source:stackexchange.com