I have a button that generates a graph (using Chart.js):
<canvas id="graph"></canvas>
<script>
$("#button").click(function() {
let ctx = $("#graph");
let myChart = new Chart(ctx, {/* My nice graph. */});
});
</script>
But each time the button is pressed a new graph is created above the old graph. So then I have a lot of graphs. With jQuery I need to delete or empty the graph element and recreate it everytime the button is pressed.
CodePudding user response:
You can destroy it first like so:
<canvas id="graph"></canvas>
<script>
let myChart;
$("#button").click(function() {
if(Chart.getChart(myChart)) {
myChart.destroy();
}
let ctx = $("#graph");
myChart = new Chart(ctx, {/* My nice graph. */});
});
</script>