Google chart is not taking full width while jquery show and hide

None picture None · Dec 31, 2013 · Viewed 12.9k times · Source

I am making a google chart whith show and hide functionality.Means chart will be hidden on the page load and when user clicks a button chart will be made visible. My code

<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
    var items = $(".label1").text();
    var data = google.visualization.arrayToDataTable([
        <%= chartItems %>
    ]);
    var options = {
        title: 'Poll Results'
    };

    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
    chart.draw(data, options);
}
</script>
<div id="chart_div" style="display:none; width:800px;height:500px;"></div>

My problem is that when user clicks on the button and chart is visible its not taking the full width and height(800x500).rather its taking an unknown dimension(400x200). Note: when the chart is made visible in the page load itself, It works correctly. Code is same change in HTML like this

<div id="chart_div" style=" width:800px;height:500px;"></div>

Answer

asgallant picture asgallant · Dec 31, 2013

You can do as marios suggested and set dimensions inside that chart's options, but that won't fix all of the problems that come along with drawing a chart inside a hidden div. The Visualization APIs dimensional measurements don't work well inside hidden divs, so elements get positioned in the wrong place and have the wrong size in some browsers. You need to unhide the div immediately prior to drawing the chart, and you can hide it again when the chart is done drawing. Here's example code that does this:

var container = document.getElementById('chart_div');
container.style.display = 'block';
var chart = new google.visualization.PieChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
    container.style.display = 'none';
});
chart.draw(data, options);