vabm vabm - 3 months ago 37
HTML Question

Trigger window resize on bootstrap collapse

I am having sizing problems with a c3.js chart I have placed in a bootstrap collapse div. Similar to this question. Following the answers, I am trying to trigger a window resize each time the c3 chart is loaded, but does not seem to work. I know it's kind of a basic question (jquery ignorant), but how can I run

$(window).trigger('resize');
each time I load the chart or open the panel-collapse div?

html:

<div class="col-sm-4">
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#collapse4"><center>Title</center></a>
</h4>
</div>
<div id="collapse4" class="panel-collapse collapse">
<div id="chart3"></div>
<div class="panel-footer"></div>
</div>
</div>
</div>
</div>


js:

$(function () {
var chart = c3.generate({
bindto: '#chart3',
data: {
columns: [
['data1', 30],
['data2', 50]
],
type: 'donut',
}
});
$(window).trigger('resize');
});

Answer

Bind to the .click() event:

$(document).ready(function() {
  $(".panel-collapse collapse").click(function() {
    $(window).trigger('resize');
  });
});

For the chart load, it'll depend on how you're calling it to be generated. If c3.generate() is the graph load function, then create another wrapping function, which calls both c3.generate() and $(window).trigger('resize'); then always load the chart with that:

function generateAndResizeWindow(options) {
  options.onrendered = function() { $(window).trigger('resize') }; // or whatever function generates your graph
  c3.generate(options);
}

then call as:

generateAndResizeWindow({
    bindto: '#chart3',
    data: {
        columns: [
            ['data1', 30],
            ['data2', 50]
        ],
        type: 'donut',
    }
});

for your example.

Comments