0
votes

There are 2 charts and 1 common legend in one page. This legend is clickable to show/hide graph line of charts. This is forked this question.

I had tried to update data above code. It's an unrefined way, but i've been able to update the chart. "The legend" text will hide/show a line chart in here.

However after the update data, this toggle function is not work.

Please try here.

  1. Click "The legend", it show and hide graph line --->OK

  2. Click "ChangeData" button, graph line will be changed --->OK

  3. Click "The legend" again, does not disappear graph line -->NG

First, it call the DrawChart function, which draws the data for the argument.

window.onload = function () {
 DrawChart(data_A1, data_B1);
 clickableCommonLegend();
}  

The DrawChart function draw line chart by typical method of ChartJS.

 function DrawChart(data_A, data_B) {
            var ctxA = document.getElementById("myChartA").getContext("2d");
            var ctxB = document.getElementById("myChartB").getContext("2d");

             myChartA = new Chart(ctxA, {
                type: 'line',
                data:{.....
                options:{....
              });
              myChartB = new Chart(ctxB, {
                type: 'line',
                data:{.....
                options:{....
              });

The clickableCommonLegend() is forked from this question.

On click button function that calls "changeData()". This function execute destroy charts and reCall "DrawChart"

function changeData() {
  myChartA.destroy();
  myChartB.destroy();
  DrawChart(data_A2, data_B2);
  myChartA.update();
  myChartB.update();

  clickableCommonLegend();
}

I guess that destroy() delete all context of and re-define context by document.getElementById("myChartA")... in DrawChart(). I think it wii work fine, but result is not.

in clickableCommonLegend,

var legendItems = document.querySelector('.legend').innerHTML = myChartA.generateLegend();

Does legendItems removed from chart.destroy? But I call it again.

I'm grad if you let me know what is wrong.

Current code is present here.

1

1 Answers

0
votes

I've found a solution.

Change changeData() function

function changeData() {

//  ---NOT WORK---
// myChartA.destroy();
// myChartB.destroy();
// DrawChart(data_A2, data_B2);

// --- OK ---        
  myChartA.data.datasets[0].data = data_A2;
  myChartB.data.datasets[0].data = data_B2;
  myChartA.update();
  myChartB.update();

  clickableCommonLegend();
}