Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Charts in tabs - chart size and position incorrect in hidden tab

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.

like image 442
user3049880 Avatar asked Nov 29 '13 16:11

user3049880


2 Answers

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:

  1. draw the charts before you initialize your tabs, so all divs are visible at draw time
  2. set up event handlers on your tabs to draw all charts within a tab when it is first opened
  3. unhide all divs immediately prior to drawing the charts, then re-hide divs as necessary in "ready" event handlers for the charts
like image 98
asgallant Avatar answered Sep 20 '22 02:09

asgallant


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.

like image 20
technoTarek Avatar answered Sep 19 '22 02:09

technoTarek