[Chartjs]-Chart JS Re-Animate chart with onclick

4👍

You need to destroy it, and create it again :

var ctx = document.getElementById("myChart");

var config = {
  type: 'bar',
  data: {
    labels: ["2014", "2015", "2016"],
    datasets: [{
      label: 'Group 1',
      data: [50, -59, 64],
      datalabels:{
        anchor: "end",
        align: "end",
        color:"black",
        font:{ size: 14, },
      },
      backgroundColor: [ '#5bbbbb', '#5bbbbb4', '#5bbbbb' ],
      borderWidth: 1
    },{
      label: 'Group 2',
      data: [69, -85, 92],
      datalabels:{
        anchor: "end",
        align: "end",
        color:"black",
        font:{ size: 14, },
      },
      backgroundColor: ['#ddd','#ddd','#ddd'],
      borderWidth: 1
    }]
  },

  options: {
    scales: {
      yAxes: [{
        ticks: {
        beginAtZero:true,
        max:100
        }
      }]
    }
  }
};

var chart = new Chart(ctx, config);


(function() { // self calling function replaces document.ready()

//adding event listenr to button
    document.querySelector('#button1').addEventListener('click',function(){

    chart.destroy();
    chart = new Chart(ctx, config);
});

})();

And here is a fiddle : http://jsfiddle.net/f7nj80ye/30/

Leave a comment