Search code examples
javascripthtml5-canvaschart.jsdefault

Update all Chart.js instances in order to apply changed defaults?


Situation:

I'm currently integrating a dynamic dark theme feature and need to change the defaults of Chart.js on a change of the theme. It looks something like this (highly simplified):

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';
  }
}


Problem:

The existing charts on the page don't immediately apply the changed default settings. Only on an update they do (e.g. on tooltip, change of data, resize of canvas).

I can manually update a chart by calling the instance method .update() of Chart. But I don't have access to all existing chart objects (no access to scope of the scripts creating them) and I didn't found a way to get them globally.


Question:

  1. Is there a way to force an update on all charts without their Chart instances?
  2. or: Is there a way to get all the chart instances to then update them all?
  3. or: Is this an XY Problem and there is a way to fix this I'm not thinking about?

I would already be satisfied with an answer to one of the above questions.


Example to reproduce the problem:

Show and run the code snippet. Hit the "toggleDarkTheme" button and click on "# of Votes" or something else to trigger an update.

// 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';
  }
}
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
      }
  });
  document.getElementById('triggerManualUpdate').addEventListener('click', ()=>{
    myChart.update();
  });
}
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/[email protected]/dist/Chart.min.js"></script>
<div>
  <button id="toggleDarkTheme">toggleDarkTheme</button>
  <button id="triggerManualUpdate">triggerManualUpdate</button>
</div>
<canvas id="myChart" width="400" height="400"></canvas>


Solution

  • 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/[email protected]/dist/Chart.min.js"></script>
    <div>
      <button id="toggleDarkTheme">toggleDarkTheme</button>
    </div>
    <canvas id="myChart" width="400" height="400"></canvas>