To ensure the Google Chart is responsive when it loads for the first time, one approach is to dynamically set its dimensions.
CSS
#chart_div {
width: 1200px !important;
height: 700px !important;
}
@media (max-width: 992px) {
#chart_div {
width: 350px !important;
height: 400px !important;
}
}
HTML
<div style="text-align: center;">
<div id="chart_div" style="display: inline-block;"></div>
</div>
JavaScript
var currentChartType = 'total';
function adjustChartDimensions() {
var chartDiv = document.getElementById('chart_div');
if (window.innerWidth <= 992) {
chartDiv.style.width = '350px';
chartDiv.style.height = '400px';
} else {
chartDiv.style.width = '1200px';
chartDiv.style.height = '700px';
}
}
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(function () {
adjustChartDimensions();
drawSelectedChart(currentChartType);
});
function displayChart() {
// Your existing data and options setup
var data = /* your data */;
var options = {
chart: {
title: 'Acres Over Time for Serial Numbers',
subtitle: 'Date vs Acres',
},
hAxis: {
format: 'd MMM',
gridlines: {
count: 7 // example
},
minorGridlines: {
count: 0
}
},
vAxis: {
title: 'Total Area',
}
};
var chartDiv = document.getElementById('chart_div');
var chart1 = new google.visualization.LineChart(chartDiv);
chart1.draw(data, options);
window.addEventListener('resize', function() {
adjustChartDimensions();
displayChart();
}, false);
}
function displayTimeChart() {
// Your existing data and options setup for time-based chart
// ...
var chartDiv = document.getElementById('chart_div');
var chart2 = new google.visualization.LineChart(chartDiv);
chart2.draw(data, options);
window.addEventListener('resize', function() {
adjustChartDimensions();
displayTimeChart();
}, false);
}
function showSelectedChart(selectedChartType) {
if (selectedChartType === 'default') {
drawDefaultChart();
} else if (selectedChartType === 'time') {
displayTimeChart();
} else if (selectedChartType === 'total') {
displayChart();
}
}
function switchCharts() {
var chartSelector = document.getElementById('chartSelector');
var selectedChartType = chartSelector.value;
currentChartType = selectedChartType;
showSelectedChart(currentChartType);
}
In this code snippet, I introduced a function named adjustChartDimensions
which adapts the chart size according to the window width. It is initially called after the loading of Google Charts and is also triggered upon window resize events. This method helps address the responsiveness and initial sizing concerns.