[Chartjs]-Chart.js – dynamically added chart makes previous ones disappear

1👍

Your code looks fine to me and I don’t know why the first chart is not shown. Looking at the DOM in Chrome DevTools, I see that both canvas are correctly added to the div‘s innerHTML.

The problem can be solved. Instead of using the div‘s innerHTML, you can use document.createElement() for creating the child div and it’s canvas, then Node.appendChild() to add the new structure to the DOM as follows:

let canvas = document.createElement('canvas');
canvas.setAttribute('id', 'chart_' + name);
canvas.setAttribute('width', '250');
canvas.setAttribute('height', '200');
let canvasContainer = document.createElement('div');
canvasContainer.appendChild(canvas);
document.getElementById("charts").appendChild(canvasContainer); 

The same could be done throgh two lines of code by using the jQuery .append() function as follows:

let chartContainer = $(`<div><canvas id="chart_${name}" width="140px" height="140px"></canvas></div>`);
$('#charts').append(chartContainer);

Please take a look at your amended code below and see how it works.

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js" integrity="sha512-QSkVNOCYLtj73J4hbmVoOV6KVZuMluZlioC+trLpewV8qMjsWqlIQvkn1KGX2StWvPMdWGBqim1xlC8krl1EKQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<div id="charts"></div>

<script>
  let dict = new Object();

  function addData(name, data) {
    let chart = dict[name];
    if (!chart) {    
      chart = addChart(name);
      dict[name] = chart;
    }
    chart.data.labels.push(new Date().toLocaleTimeString());
    chart.data.datasets.forEach(dataset => dataset.data.push(data));
    chart.update();
  }

  function addChart(name) {
    let data = {
      labels: [],
      datasets: [{
        label: name,
        backgroundColor: 'rgb(255, 99, 132)',
        borderColor: 'rgb(255, 99, 132)',
        data: [],
      }]
    };    
    let config = {
      type: 'line',
      data: data,
      options: {
        responsive: false,
        maintainAspectRatio: true,
      }
    };
    
    let canvas = document.createElement('canvas');
    canvas.setAttribute('id', 'chart_' + name);
    canvas.setAttribute('width', '250');
    canvas.setAttribute('height', '200');
    let canvasContainer = document.createElement('div');
    canvasContainer.appendChild(canvas);
    document.getElementById("charts").appendChild(canvasContainer);

    return new Chart(`chart_${name}`, config );   
  }

  addData("TEST1", 1);
  addData("TEST1", 2);
  addData("TEST2", 1);
  addData("TEST2", 3);
</script>

Leave a comment