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>
This problem happens when on your page load and your container is responsive and does not have a definite width yet, Google Chart use 400 width as default when it detected the parent container width returns 'NaN'. But Google chart works fine if you load the chart on click were the elements are properly loaded.
After Google Chart Updates as of Sep 2021, the most quick fix on loading dynamic charts take the full width of its container is to load it with delay. setTimeout (function () { chart.draw (view, options); }, 2000 );
One very common option to set is the chart height and width. You can specify the chart size in two places: in the HTML of the container <div> element, or in the chart options.
setTimeout (function () { chart.draw (view, options); }, 2000 ); This problem happens when on your page load and your container is responsive and does not have a definite width yet, Google Chart use 400 width as default when it detected the parent container width returns 'NaN'.
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);
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