nunya
nunya

Reputation: 315

Change/Swap Highcharts Data

I've set-up a Pie Chart using Highcharts and I need to swap the data out via buttons. The second button (Distant) swaps out the data no problem but when I try to swap back to the original data with the first button (Immediate) it doesn't work.

Here is my Codepen: https://codepen.io/doitliketyler/pen/mQMyGe?editors=1011

My buttons look like this:

$('#immediate').click(function() {
  chart.series[0].setData(immediate);
});

$('#distant').click(function() {
  chart.series[0].setData(distant);
});

Any ideas on how this is done properly?

Upvotes: 0

Views: 87

Answers (1)

nitrodmr
nitrodmr

Reputation: 198

Here you go. The problem was that when you set one of your data array, it passes by reference so both data sets are pointing at the same thing. So first make a copy of the data you want to set. Then set an empty array as your data to clear highcharts data then set it with the copy array.

var chart = Highcharts.chart('container', {
  chart: {
    type: 'pie'
  },
  title: {
    text: 'Swap Pie Data'
  },
  series: [
    {
      id: 'relative',
      name: 'Immediate',
      type: 'pie',
      size: '100%',
      innerSize: '30%',
      colorByPoint: true,
      data: immediate
    },
    {
      type: 'pie',
      size: '30%',
      name: 'Original',
      colorByPoint: true,
      data: original
    }
  ]
});

$('#immediate').click(function() {
  var temp = immediate.slice(0);

  chart.series[0].setData([]);
   chart.series[0].setData(temp);

});

$('#distant').click(function() {
    var temp = distant.slice(0);

    chart.series[0].setData([]);
    chart.series[0].setData(temp);
});

Upvotes: 1

Related Questions