Clear/Reinitialize Highchart

Clear/Reinitialize Highchart

I'm using Highcharts.js plugin at the moment everything it's ok but while I was testing my char I discovered that if a call my draw chart function twice I get the results that I expect two times, so now I want to clear chart content or reinitialize or destroy or whatever before call it again but I don't know exactly what to do, searching here for a solution I found this:

myChar.destroy();

But in this case myChar is a variable where they put all the chart options and my problem is that I do this in a function, so what can I do to create a reset function for example, here is my code and what I tried:

$(document).ready(function() {
  $('#bt').click(function() {
    chart();
  });
  $('#bt2').click(function() {
    $('#MyDiv').html("");
  });
});

function chart() {

  $('#Chart').highcharts({
    chart: {
      type: 'bar'
    },
    title: {
      text: 'Inspeccion Dimensional'
    },
    xAxis: {
      categories: ['Pieza 1', 'Pieza 2', 'Pieza 3', 'Pieza 4', 'Pieza 5']
    },
    yAxis: {
      min: 0,
      title: {
        text: 'Resultados'
      }
    },
    legend: {
      reversed: true
    },
    plotOptions: {
      series: {
        stacking: 'normal'
      }
    },


    series: [{
      name: 'Thickness',
      data: [2, 2, 3, 2, 1]
    }, {
      name: 'Width',
      data: [2, 2, 3, 2, 1]
    }, {
      name: 'Length',
      data: [2, 2, 3, 2, 1]
    }, {
      name: 'Diameter',
      data: [3, 4, 4, 2, 5]
    }]
  });
}
<script src=""></script>

<script src=""></script>
<script src=""></script>


<button id="bt">
  Draw
</button>

<button id="bt2">
  Clear
</button>

<div id="MyDiv">
  <div id="Chart">
  </div>
</div>

If you see my code I tried to solve this using $('#MyDiv').html("") but if I do this in this way I'm not able to draw my chart again. Fiddle with working code

1

2 Answers

You need to destroy the instance of Highchart.

$('#bt2').click(function () {
    $('#Chart').highcharts().destroy();
 });

Updated Fiddle

add the following code in the button 2 event:

$('#Chart').highcharts().destroy();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.