[Chartjs]-Re-running chart.js with different variable

1๐Ÿ‘

โœ…

If you instead of declaring the variable in your ajax request, declare it beforehand and check if there is an active chart and destroy that first then your behaviour will go away.

var chart = null;

const addChart = (chartConfig) => {
  if (chart) chart.destroy();

  var ctx = document.getElementById('chartJSContainer').getContext('2d');
  chart = new Chart(ctx, chartConfig);

  chart.update(); 
}

Working sample:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          reverse: false
        }
      }]
    }
  }
}

var options2 = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          reverse: false
        }
      }]
    }
  }
}

var chart = null; // DECLARE BEFOREHAND

var option1 = true;

const addChart = (chartConfig) => {
  if (chart) chart.destroy(); // DESTROY CHART IF EXISTS

  var ctx = document.getElementById('chartJSContainer').getContext('2d');
  chart = new Chart(ctx, chartConfig);

  chart.update();
  option1 = !option1;
}

document.getElementById('myButton').addEventListener("click", () => {
  option1 ? addChart(options) : addChart(options2);
});
<body>
  <button id="myButton">
Gen Chart
</button>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>

Fiddle: https://jsfiddle.net/Leelenaleee/6gf0hs9q/19/

Leave a comment