Roby Sottini
Roby Sottini

Reputation: 2265

How to reload a jQuery element when a button is pressed

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.

Upvotes: 1

Views: 210

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31421

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>

Upvotes: 1

Related Questions