Reputation: 2315
I was having some trouble with doughnut chart by using chart.js. The problem is when I update the graph, and when I hover over the graph, sometimes it shows the old chart. Here is where I call the function to plot chart:
<select class="form-control" id="ddlCategory" onchange="plotChart()">
</select>
function plotChart(){
// removed code to retrieve data from firebase
var chart;
var ctx = document.getElementById('donutChart').getContext("2d");
var data = {};
var opt = {
type: "doughnut",
data: data,
options: options
};
if (chart) {
chart.destroy();
chart.clear();
}else{
chart = new Chart(ctx,opt);
}
for(var i = 0; i < labelData.length; i++){
chart.config.data.labels.push(labelData[i]);
}
chart.update();
}
I tried to destroy the previous chart before I update it but to no avail. Any ideas?
Upvotes: 2
Views: 4272
Reputation: 32879
You indeed need to destroy the previous chart. Perhaps try with the following :
function plotChart() {
// removed code to retrieve data from firebase
var ctx = document.getElementById('donutChart').getContext("2d");
var data = {};
var opt = {
type: "doughnut",
data: data,
options: options
};
if (chart) chart.chart.destroy();
window.chart = new Chart(ctx, opt);
for (var i = 0; i < labelData.length; i++) {
chart.config.data.labels.push(labelData[i]);
}
chart.update();
}
Upvotes: 2
Reputation: 92
It seems that your chart variable is being redeclared everytime the function is called and hence will never exist when you call plotchart(). Would recommend that you declare the variable before and bring it into the correct scope if it exists. That seems to be the core of your problem
Upvotes: 1