Joe
Joe

Reputation: 69

HTML Canvas height defaults to 1 after slideToggle

I have the following code to define a chart inside of a js file.

"<div class='col-10 col-md-3 col-lg-3' id='" + firstName + lastName + 
       primaryCompensationCode + "COLME' style='position: relative;'>",
"<canvas id="firstName + lastName + primaryCompensationCode + "ME",
" height='260' width='260' responsive></canvas>",
"</div>",

The code is in the form of a string, because I build the layout of the chart within a card and append that to the document. I also have a function that will expand and collapse the card, including the charts, but this is where the issue lies. After expanding the chart after collapsing it, or adding more cards, the chart height defaults to 1 while the width auto-adjusts to fill the space. I cant see any reason why the height wouldn't auto adjust as well and at no point am I defining a height and width besides when the chart is constructed. Any thoughts?

Here's what it looks like when you first open the card: Open

and here's what it looks like when you close and re-open the card: Open2

and here's where the height is defaulting to 1:

Open3

There are three charts and an image all contained in the body of a card. When the header of the card is clicked, the following function is called which collapses the card into the card header.

expandCard: function(clicked_id) {
    var advisorCard = document.getElementById(clicked_id);
    $(advisorCard).nextUntil('div.card-header').slideToggle(1);
}

When the elements load into the page, the cards are collapsed by default. So here's where the issue is: If you add a card (card1) and don't expand it, then add another card (card2). Then card2 expands and shows the charts just fine, whereas card1's charts have a height of 1. The div that contains each chart (the bootstrap column) also has a height of 1 in this scenario.

Upvotes: 0

Views: 180

Answers (1)

jmcgriz
jmcgriz

Reputation: 3358

According to this: https://www.chartjs.org/docs/latest/general/responsive.html#important-note, looks like for the responsive attribute to work correctly, the parent element needs to be sized using relative units. Their code example is:

<div class="chart-container" style="position: relative; height:40vh; width:80vw">
    <canvas id="chart"></canvas>
</div>

Upvotes: 1

Related Questions