Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

250
Views
chart.js - dynamically added chart makes previous ones disappear

Basically

Whenever I call addData like

addData("TEST1", 1);

or

addData("TEST2", 1);

then I'm checking whether chart named "TEST1" already exists and if it does then I return chart object and if it doesn't then I create new

and then I insert data on it

and it works to the point that when I create e.g 2nd chart, then first one disappears

but why?

<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>
var dict = new Object();

function addData(name, data) 
{
    var chart = dict[name];
    if (chart == undefined)
    {
        console.log("adding chart:"  + name);
        chart = AddChart(name);
    }
    else
    {
        console.log("skipping chart creation:"  + name);
    }
        
    chart.data.labels.push(new Date().toLocaleTimeString());
    chart.data.datasets.forEach((dataset) => 
    {
        dataset.data.push(data);
    });
    chart.update();
}


function AddChart(name)
{
    const data = 
    {
        labels: [],
        datasets: [{
            label: name,
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: [],
        }]
    };

    const config = 
    {
        type: 'line',
        data: data,
        options:
        {
            responsive: false,
            maintainAspectRatio: false,
        }
    };

    var cont = document.getElementById("charts");
    cont.innerHTML += `<div width="140px" height="140px"><canvas id="chart_${name}"></canvas></div>`;

    const myChart = new Chart
    (
        document.getElementById(`chart_${name}`).getContext('2d'),
        config
    );

    dict[name] = myChart;

    console.log("added");
    console.log(dict);
    return dict[name];
}

addData("TEST1", 1);
addData("TEST2", 1);
</script>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!