jquerygoogle-visualizationjquery-tabs

Google Charts With Tabs - Chart Area Incorrect


Although this may seem a common problem but i was not able to find a solution to this particular problem..

I am trying to create 2 pie charts using GOOGLE CHARTING API..

The 1st Pie chart which is in the 1st TAB (default selected) shows the accurate width and height but the 2nd pie chart in the hidden tab does not show appropriate width..

Here is the fiddle...

In the Fiddle we can see the chart area in the hidden tab is less than the chart area in the active tab although the code for both the charts is the same...

google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);

function drawChart() 

{

var data = google.visualization.arrayToDataTable([
      ['Task', 'Hours per Day'],
      ['Work',     11],
      ['Eat',      2],
      ['Commute',  2],
      ['Watch TV', 2],
      ['Sleep',    7]
    ]);

 var options = {
      title: 'My Daily Activities',
  backgroundColor: '#ddd',
  chartArea: {width:500,height:200}
    };

var chart = new      google.visualization.PieChart(document.getElementById('chart'));


chart.draw(data, options);

var chart1= new      google.visualization.PieChart(document.getElementById('chart1'));


chart1.draw(data, options);
}

Update the fiddle if you can here..


Solution

  • I have half an answer for you. I can see what's happening, I can see a workaround, but I'm not sure yet why it's happening...

    When you call .draw the vis api tries to calculate a 'best-fit' based on the dimensions of the container that it is being drawn in.

    Your problem is that your container divs start off at different sizes

    Change

    #content_2, #content_3 { display:none; }
    

    to

    #content_2, #content_3 { display:block; }
    

    to see...

    A workaround that fixes the problem is to 'init' the div inside the tab box by firing off the click event before drawing the chart with a

    $(".tabs a[title='content_2']").click()
    $(".tabs a[title='content_1']").click()
    

    It looks ugly on the fiddle, but you can tidy that by playing with the display options

    Here's the fiddle as a demo

    Hope that helps