Chartjs-Why canvas content, line chart chart.js, doesn't show on bootstrap popover body?

0👍

So, I got it working.

I forked your CodePen, so you can see the functioning solution here.

Your canvas element needs to already be in the DOM before you draw the chart. So, I changed the code so that only the canvas element is inserted in the popover. Then, I added an event listener for the bootstrap event "inserted.bs.popover", which is called after the popover is inserted into the DOM. Here’s the documentation for Bootstrap popover events.

Adding that event listener looks like this code:

$("[data-bs-toggle='popover']").on("inserted.bs.popover", () => {
  // Invoke Chart.js to draw the chart
  new Chart("myCanvas", chartjsConfig);
});

I hope that helps with your question.

Accessibility Aside

Since you are looking to incorporate accessibility into your charts, I also added some extra accessibility code to that codepen. I work on an open source library, Chart2Music, and I added its chartjs plugin to your code. You can play with it yourself by:

  1. Press the TAB key until you get to the "Open Chart" button.
  2. Press SPACEBAR to open the button (this was done by Bootstrap)
  3. Press TAB again. You’ll focus on the chart in the popover.
  4. Press the left/right arrow keys. You’ll move around the chart, and hear sounds ("sonification") to represent the values.

I added comments before the lines that are specific to Chart2Music, so hopefully it’s not confusing.

Let me know if you have any questions!

Leave a comment