I have a set of two tabs. Each tab has a Google chart inside it. Both these charts should be identical in terms of size and position.
When the page is loaded, the position of the chart is how I want it (regardless of which tab you are initially on). When you then move to the other tab (initially hidden) the chart's position and sizing changes.
You can see this in the example here: http://cb.tortoise-dev.co.uk/
To simplify things I've added fixed widths and heights to the chart container, but this hasn't helped. I'm pretty sure that the problem is to do with the hidden container having no dimensions when the page is loaded and the chart being drawn to a sort of default size rather than filling the container (like it does in the initially visible tab). I'm not sure what the solution is though.
Any help would be greatly appreciated. Thanks in advance.
Your suspicion is correct: if the chart's container div (or a parent element) is hidden when the draw call is made, the Visualization API's dimensional measurements get messed up, and effects like the one you've noticed show up. There are a few different solutions you can go with:
For Twitter Bootstrap users, I've found the following js snippet to be pretty useful. It's a way of using the second solution as provided by @asgallant and takes advantage of the built in Bootstrap Tab events documented at http://getbootstrap.com/javascript/#tabs-events.
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
if($(e.target).attr('id') == 'first-tab-trigger')
{
drawFirstChart();
}
if($(e.target).attr('id') == 'second-tab-trigger')
{
drawSecondChart();
}
})
The snippet requires that you add a unique class or id selector to your tab like so (e.g., class="first-tab-trigger" etc):
<ul class="nav nav-tabs">
<li class="active">
<a href="#section-one" id="first-tab-trigger" data-toggle="tab">
FIRST TAB
</a>
</li>
<li class="col-sm-3">
<a href="#section-two" id="second-tab-trigger" data-toggle="tab">
SECOND TAB
</a>
</li>
...
</ul>
Now, when a tab is clicked and the the tab's content is made visible, a drawing (or re-drawing) of the chart takes place. That solves the sizing problems you get when you have charts in hidden tabs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With