Initial loading size of Google chart

After creating a Google chart, I noticed that on the initial load, the chart appears tiny. Although it becomes responsive when adjusting the screen size, I would prefer it to be responsive from the start.

Please note that there is a dropdown menu for selecting different charts.

Below is the code snippet for reference:

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:

// Javascript functions for drawing and switching between charts...

In my attempts to address this issue, I have experimented with hardcoding sizes in options as well as using CSS styling for responsiveness. While these solutions partly work, they do not fully meet my requirements as the chart remains tiny upon initial loading.

Answer №1

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extracting information from a recordset and displaying it in an HTML division

Currently, I am developing an Inventory Manager system to keep track of a variety of fishing equipment. Through HTML forms, I am able to input data into a SQL server database. My goal is to load data from a select statement into a specific div on my index. ...

Utilizing dynamic content to pass arguments to JavaScript functions

I'm facing a challenging issue that is causing me frustration. While browsing through this platform, I found some potential solutions but encountered a roadblock in implementing them successfully. My current project involves developing an e-commerce p ...

Retrieve the HTML content starting from the nth tag and beyond

I am currently working on a table... <table class="col-xs-12"> <thead class="testhead col-xs-12"> <tr class="col-xs-12" id="row1" style="color: white;"> <th>0</th> ...

In PHP, the use of ul, li, class, and

I have searched high and low, but unfortunately the answers provided by others did not alleviate my problem. Instead, they caused even more confusion. I am currently working on a small project for my website and attempting to convert it to PHP in order to ...

Unexpected issues have arisen with the $.ajax function, causing it

I am facing an issue where I can see the loader.gif but unable to view avaiable.png or not_avaiable.png in my PHP file. What could be causing this problem? $(document).ready(function()//When the dom is ready { $("#inputEmail").change(function() { ...

Efficiently map nested properties of this.props within the render method

When working in the render() method, I find myself passing numerous variables around. The recommended best practices suggest setting up variables before the return <div>...etc</div statement like this: const { products: mainProducts, ...

The ion-datetime-button within an ion-item does not have full height

I am experiencing an issue where the ion-items containing ion-select and ion-datetime-button elements do not have consistent heights. Even though they are all nested within ion-cols with identical properties. The ion-items with ion-datetime-buttons appear ...

How can we incorporate Django template tags into our jQuery/JavaScript code?

Is it possible to incorporate Django's template tags within JavaScript code? For example, utilizing {% form.as_p %} in jQuery to dynamically inject forms onto the webpage. ...

Can the html content provided by the user be extracted and highlighted?

When utilizing the onClick function in ReactJS, I am receiving the entire property which includes Lorem Ipsum is simply dummy text. However, I only require the highlighted content like "is simply dummy". Is there a way to achieve this?</p> ...

Show and hide a div with the click of a button

As I embark on rebuilding a website from the ground up, I find myself pondering how to achieve a specific functionality: My goal is for another view to appear when one of two buttons is clicked. How can this be accomplished? I attempted the following app ...

Convert js.executeAsyncScript result into a Map with key-value pairs of strings

Trying to convert the output of the script below into a Map<string,string>, but encountering an error that says "java.lang.String cannot be cast to java.util.Map". How can I successfully cast it as a map? final JavascriptExecutor js = (Ja ...

Ways to incorporate custom CSS alongside Bootstrap styling

Just starting out with CSS and HTML I've applied some Bootstrap styles to my HTML elements But when you use a bootstrap style, the class is automatically taken over. This means I can't add my own custom CSS styles. Is there any workaround for thi ...

Sending formdata containing a file and variables via $.ajax

I've been working on a jquery file upload project based on a tutorial I found here: . The tutorial is great and the functionality works perfectly. However, I'm looking to add more control and security measures for user image uploads, such as inco ...

React component causing footer overlap

Currently, I'm facing a challenge in creating a footer that stays at the bottom of the page without overlapping any other components. In my index file, I've included the following code: .footer{ margin-top: 1rem; padding: 1rem; background- ...

Ways to collapse all rows that are expanded except the one that is currently open in iView Tables

Utilizing iView Tables to display data in a table with an expand option. As of now, when clicking on the expand button for a row, the row expands but previously expanded rows do not collapse, causing all expanded rows to be visible at once. Is there a wa ...

Setting a page title using PHP based on a conditional statement can be achieved by

I am attempting to display a different title for each page In the header.php file, I am checking the file name to set the correct title like this <?php $page = basename($_SERVER['PHP_SELF']); if ($page == 'index.php'): ?> <ti ...

Incorporating a Drawer and AppBar using Material-UI and React: Dealing with the error message "Unable to access property 'open' of null."

Currently, I am working on developing an app using React and Material-UI. I have successfully implemented the AppBar component, but I am facing difficulties with setting up the Drawer functionality. The main issue I am encountering is an error message sta ...

Filtering an unsorted list through the URL parameter of #value when the page is first

I am currently working on building a portfolio website and have encountered some difficulties with filtering the portfolio elements using Javascript / Jquery. Since I am new to this, I am keeping things simple by implementing a basic filter that shows or h ...

Sign up for and run a JavaScript function within an ASP.NET Page_Load event

Is there a way to both register and run a JavaScript function in ASP.NET during a Page_Load event? I need the function to validate the content of a textbox, and if it is empty, disable a save button. function Validate(source, arguments) { } ...

Trigger the onClick event of an element only if it was not clicked on specific child elements

<div onClick={()=>do_stuff()}> <div classname="div-1"></div> <div classname="div-2"></div> <div classname="div-3"></div> <div classname="div-4"></div> ...