Chartjs-Why is Chart.js not attaching a second Chart when adding the container with javascript?

0πŸ‘

βœ…

The dom gets edited so the chart that is rendered is now getting a new canvas without you re making the chart, this can be fixed by first adding the canvases to the dom before creating the charts:

const container = document.getElementById("container")
container.innerHTML += '<canvas id="myChart2"></canvas>'
container.innerHTML += '<canvas id="myChart"></canvas>'

const config = {
  type: 'line',
  data: data,
  options: {}
}

// Make Chart
const myChart1 = new Chart(
  document.getElementById('myChart'),
  config
)

// Second Chart

const config2 = {
  type: 'bar',
  data: data,
  options: {}
}

// Add Chart-JS Container
const myChart2 = new Chart(
  document.getElementById('myChart2'),
  config2
)

https://codepen.io/leelenaleee/pen/PoeKxBZ

0πŸ‘

You need to add a new div for each new chart for it to work.

index.html

<div id="container"></div>
// Add a new div for the 2nd chart
<div id="container2"></div>

index.js

// ...

// Declare the var for the 2nd div container
const container2 = document.getElementById("container2")

// Add Chart-JS Container using the 2nd div
container2.innerHTML += '<canvas id="myChart2"></canvas>'
const myChart2 = new Chart(
  document.getElementById('myChart2'),
  config2
)

Working codepen here https://codepen.io/SuperNoobi/pen/rNvzQQr

0πŸ‘

You need to initialize the charts once the DOM is loaded:

...

document.addEventListener("DOMContentLoaded", () => {
  // Make Chart
    const myChart1 = new Chart(
      document.getElementById('myChart'),
      config
    )

    const myChart2 = new Chart(
      document.getElementById('myChart2'),
      config2
    )
});

...

Pen: https://codepen.io/mavyfaby/pen/xxjLQQM

Leave a comment