Achieve responsiveness for Google Chart Gauge

I am trying to create a Google Gauge chart that is web-responsive, but setting the width to '100%' is not working as expected. Here is the code I am using:

<script type='text/javascript'>
      google.load('visualization', '1', {packages:['gauge']});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Label', 'Value'],
          ['Happiness', 40],
        ]);

        var options = {
          width: '100%', height: '100%',
          redFrom: 0, redTo: 40,
          yellowFrom: 40, yellowTo: 70,
          greenFrom: 70, greenTo: 100,
          minorTicks: 5
        };

        var chart = new google.visualization.Gauge(document.getElementById('test'));
        chart.draw(data, options);
      }
    </script>

You can view an example here.

If you know how to make this chart web-responsive, please let me know. Thank you!

Answer №1

In order to make the charts resize automatically, you will need to set up an event handler that triggers the chart.draw(data, options); function upon resize:

function drawChart () {
    var data = google.visualization.arrayToDataTable([
        ['Label', 'Value'],
        ['Happiness', 40]
    ]);

    var options = {
        redFrom: 0,
        redTo: 40,
        yellowFrom:40,
        yellowTo: 70,
        greenFrom: 70,
        greenTo: 100,
        minorTicks: 5
    };

    var chart = new google.visualization.Gauge(document.getElementById('test'));
    chart.draw(data, options);

    function resizeHandler () {
        chart.draw(data, options);
    }
    if (window.addEventListener) {
        window.addEventListener('resize', resizeHandler, false);
    }
    else if (window.attachEvent) {
        window.attachEvent('onresize', resizeHandler);
    }
}

If you try to set height and width to 100% within the options, it will not have any effect. Instead, you should define these properties in the CSS for your container div:

#test {
    height: 100%;
    width: 100%;
}

Remember that setting the height to 100% will only work if the parent element has a specific height; also, the dimensions of a Gauge chart are based on the smaller of the two dimensions. Therefore, if you increase the screen size without specifying the height of the container #test (or its parent container), the chart size may not change accordingly.

Answer №2

To make a responsive div tag, you can simply set the width to 100% in the options. Alternatively, you can also use the following code snippet from this demo to see it in action.

//Insert HTML code here

 <div class="row"> 
   <div class="col-xs-12 col-sm-6">
    <div id="chart_div"></div>
  </div>
 </div>

//Insert JS code here

 var options = {'title':'How Much Pizza I Ate Last Night',
                   'width':'100%',
                  };

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

Adjust the dimensions of an image post-creation

let displayedImage = Ti.UI.createImageView({ image : somefile.png, height:'100', width:'100' }); The code above shows how I created the image. But now, I am wondering how I can resize the image after its initial creation. ...

The dynamic routing feature in React fails to function properly after the application is built or deployed

I'm facing an issue with getting a React route to function properly in the build version of my app or when deployed on Render. Here are the routes I have: <Route path="/" element={userID ? <Home /> : <Login />} /> <Route ...

Is anyone else experiencing issues with the Express middleware that checks for IDs? Looking for suggestions on how to fix

Currently working on a project with Node js utilizing Express and MongoDb for the backend. In this project, USERS have the ability to post COMMENTS, so I have created a middleware to access the DELETE route and check if the USER ID matches the ID of the in ...

Attempting to retrieve JSON data and present it in a grid layout

I have a JSON file with the following data: { "rooms":[ { "id": "1", "name": "living", "Description": "The living room", "backgroundpath":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSrsU8tuZWySrSuRYdz7 ...

Verify if a set of Radio buttons contains at least one option selected

Need help with validating a Feedback Form using either JQuery or Javascript. The requirement is to ensure that every group of radio-buttons has one option selected before the form can be submitted. Below is the code snippet from form.html: <form id=&ap ...

Header fixed vertically

I am currently working on a webpage with a minimum width requirement of 1124px. This means that whenever the browser window is smaller than that, the content of the page needs to be scrolled horizontally instead of smoothly transitioning into a responsive ...

Splitting up JavaScript and HTML within a WordPress environment

I recently came across a discussion on separating PHP code and HTML at this link I find myself in a similar predicament. My current project involves designing a WordPress website with numerous sliders, animated dropdowns, forms, and other components. The ...

Utilizing Highcharts/Highstock for handling large volumes of data efficiently

Dealing with a growing amount of data daily (currently over 200k MySQL rows in one week), the chart loading speed has become quite slow. It seems like using async loading is the solution (http://www.highcharts.com/stock/demo/lazy-loading). I attempted to i ...

Firefox and Internet Explorer do not support the functionality of HTML5 <audio> tags

My radio stream player code works perfectly on Chrome and iOS Safari, but I'm facing compatibility issues with Firefox and Internet Explorer 11. Here's a snippet from my index.php file: <script type="text/javascript" src="http://code.jquery. ...

Enhancing Symfony's performance through optimized Ajax response time

When using Symfony2, I am experiencing differences in loading times for AJAX requests between development and production environments. In development, it takes 1 second to load, while in production it only takes 500 milliseconds for a simple call: Here is ...

The PHP script's header() function is failing to execute

Recently, I encountered an issue with my JavaScript code that calls a backend PHP script using AJAX. The main function of the AJAX request is to send user login data (username and password) to the PHP script, which in turn queries this information on the S ...

What is the best way to integrate varying number formats based on user locale in UI5?

In my SAPUI5 app, I need to display numerical data based on the user's settings in the SU01 backend transaction in SAP Logon. For instance, users can specify decimal separators as: 22,000.000 (twenty two thousand) → US format 22.000,000 (twenty tw ...

Using $scope.$on name parameter as an attribute within an AngularJS directive

My goal is to create a directive that allows me to pass in an attribute string, which will then be used as the "name" parameter when subscribing to events using $scope.$on. The process involves: An object is broadcasted using $rootScope.$broadcast, label ...

Tips for achieving compatibility between systemjs module loading and .net mvc architecture

Upon finding the ng-book 2, I saw it as a promising resource to delve into Angular 2. Although I am new to module loaders and have minimal experience with npm and node, I find the terminology and assumed knowledge to be quite perplexing. I decided to use ...

Tips for updating a div element while maintaining its style and select2 plugin functionality with jQuery

Within the HTML code, I am attempting to refresh the following div: <select name="test[]" id="test" multiple required class="select2"> @foreach($tests as $s) ...

There seems to be an issue with byRole as it is failing to return

Currently in the process of migrating my unit test cases from Jest and Enzyme to React Testing Library. I am working with Material UI's Select component and need to trigger the mouseDown event on the corresponding div to open the dropdown. In my previ ...

Set the cookie to expire in 5 minutes using PHP, JavaScript, or jQuery

Is there a way to set a cookie in PHP that expires in 5 minutes? I am comfortable with the setcookie() function, but unsure about how to set the expiration time. Any explanation would be greatly appreciated. Could someone please guide me on how to achieve ...

The $scope.$watch function is not triggering events within a controller of a ui.bootstrap.modal

Currently, I am utilizing UI bootstrap for Angular and have successfully integrated the ui.bootstrap.modal component into my project. Everything seems to be working smoothly except for one issue I am encountering. Despite setting up a $scope.$watch to trac ...

The PDF file cannot be displayed due to the dynamic loading of the path and filename

Currently, I am working on an AngularJS and Java application. The following HTML code is utilized to open a PDF file in the browser. However, there seems to be an issue where the PDF does not open when dynamically passing the value for the data attribute. ...

Custom options in MUI Autocomplete are not displaying the selected option

I am currently implementing MUI v5's Autocomplete for a dropdown feature on my website. Within this dropdown, I have options that include both a title and an id. My goal is to store the selected option's id in the state while also updating the d ...