Resize the div based on the width and height of the window

My goal is to create a system or website that can be fully resizable using CSS and the VW (viewport width) unit. Within this system, I have integrated a GoogleChart that functions with pixels. Now, I am looking for a way to scale the chart using Javascript/jQuery/CSS, specifically utilizing the transform scale property. This scaling should occur upon page load.

If anyone could provide guidance in achieving this, I would greatly appreciate it.

To better illustrate the issue, here is a JSFiddle link: https://jsfiddle.net/j9a9wpdj/

// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});

// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);

// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {

  // Create the data table.
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Topping');
  data.addColumn('number', 'Slices');
  data.addRows([
    ['Mushrooms', 3],
    ['Onions', 1],
    ['Olives', 1],
    ['Zucchini', 1],
    ['Pepperoni', 2]
  ]);

  // Set chart options
  var options = {'title':'How Much Pizza I Ate Last Night',
                 'width': 400,
                 'height': 300};

  // Instantiate and draw our chart, passing in some options.
  var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
  chart.draw(data, options);
}
#test {
      width: 80vw;
  height: 40vw;
  background-color: #dcdcdc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="test">

  <div id="chart_div"></div>

</div>

[CONCLUSION] After experimenting, I found a solution that works well:

function zoomit() {
    $("#chart-wrapper").css('zoom', $(window).width() / $("#chart-wrapper").width());
}
$(document).ready(zoomit);
$(window).resize(zoomit);

Answer №1

Utilize the drawchart function to update the chart upon window resizing. Customize the width and height in the function below as needed. Enhanced example

Additional code for your script:

var width = 400;
var height = 300;

// Define chart options
var options = {
  'title': 'Amount of Pizza Consumed Last Night',
  'width': width,
  'height': height
};

$(function() {
  $(window).resize(function() {
    width = $('#test').width();
    height = $('#test').height();
    google.charts.setOnLoadCallback(drawChart);
  })
});

Demonstration of functionality:

var width = 400;
var height = 300;

// Include the Visualization API and corechart package.
google.charts.load('current', {
  'packages': ['corechart']
});

// Specify a callback to execute when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);

// Function that generates and fills a data table, creates the pie chart, adds the data, and displays it.
function drawChart() {

  // Generate the data table.
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Topping');
  data.addColumn('number', 'Slices');
  data.addRows([
    ['Mushrooms', 3],
    ['Onions', 1],
    ['Olives', 1],
    ['Zucchini', 1],
    ['Pepperoni', 2]
  ]);

  // Set chart options
  var options = {
    'title': 'Amount of Pizza Consumed Last Night',
    'width': width,
    'height': height
  };

  // Create and display the chart with specified options.
  var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
  chart.draw(data, options);
}


$(function() {
  $(window).resize(function() {
    width = $('#test').width();
    height = $('#test').height();
    google.charts.setOnLoadCallback(drawChart);
  })
});
#test {
  width: 80vw;
  height: 40vw;
  background-color: #dcdcdc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="test">

  <div id="chart_div"></div>

</div>

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

ASP.NET service with an added quotation mark in the JSON response!

I am trying to make a web service method call in JavaScript within an ASP.NET 3.5 environment. After inspecting the result using Firebug, I found the following: {"d":"[{\"TI\":\"www\"},{\"TI\":\"www1\"}]"} It seem ...

Attempting to run driver.execute_script(gooogletag but no response was received

I have been attempting to receive responses in the console from the browser when running googletag parameters with Selenium, but unfortunately I have not been successful. Even after trying .execute_async_script('googletag.pubads()') and putting ...

AngularJS expression utilizing unique special character

There are certain special characters (such as '-') in some angular expressions: <tr data-ng-repeat="asset in assets"> <td>{{asset.id}}</td> <td>{{asset.display-name}}</td> <td>{{asset.dns-name}}</td&g ...

Utilizing JSON for the setAttribute() method

While I've made progress on this issue, I've encountered numerous confusing methods. The goal is to utilize the key:value pairs in attr{} for the setAttribute() function without relying on any framework. If anyone could provide a straightforward ...

Having trouble processing the Firebase snapshot with Node.js

I have a question regarding a snapshot; ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {}) After printing the snapshot with ; console.log(snapshot.val()); This is the output that gets printed; {'-LBHEpgffPTQnxWIT ...

Is there a way to trigger an Angular $scope function from a hyperlink in the current or a new tab using a right

Here is the HTML code I am working with: <a href="" ng-click='redirectToEntity("B-",obj.id")'>Click me and Process function and then redirect</a> While this code successfully processes the function and redirects to the desired page ...

Negative margin causes content to conceal itself

I'm facing an issue with using a negative margin for positioning a label. The label is not showing up as expected. Specifically, I need to place a search box on a blue background but when applying a negative margin, the search box does not appear prop ...

What steps can I take to avoid res.send() from replacing the entire document?

When making an ajax call to insert users into the database, I want to handle the response in a specific way. If I use res.send() on the server side, it displays the response at the top left of a black document, which is not ideal. I attempted to use retu ...

Is it possible to achieve the same functionality as :first-child by employing :nth-of-type without a selector?

Currently tackling a console warning related to MUI5/emotion (I believe) I have noticed that the pseudo class ":first-child" might pose potential risks during server-side rendering. It may be worth considering replacing it with ":first-of-type". I wonder ...

Error handling: Encountered unexpected issues while parsing templates in Angular 2

I'm a beginner with Angular 2 and I'm attempting to create a simple module, but encountering an error. app.component.html import { Component } from '@angular/core'; import { Timer } from '../app/modules/timer'; @Component({ ...

Can you explain the purpose of ViewBag.LoadJQueryOnInit and ViewBag.EnableDevExpressView?

Recently, I started working at a new company and while going through the code in _Layout.cshtml, I came across the following snippet: @if (ViewBag.LoadJQueryOnInit == true || ViewBag.EnableDevExpressView == true) { <script src="/Cont ...

The jQuery UI dialog box is malfunctioning and failing to return a value when the user clicks a button

I have a jQuery UI dialog box that I want to use for confirming a deletion action with the user. The issue I am facing is that the code below seems to return "True" or "False" immediately when the dialog pops up, even before the user has clicked the "Yes" ...

Utilizing PNG images with color in CSS, HTML, or JavaScript

On my website, I have an image in PNG format. I am wondering if there is a way to change the color of the image using HTML5, JavaScript, or CSS. Ideally, I would like the image to be changed to white by inverting its colors (changing black to white, not al ...

What impact will splitting a single file into multiple files have on the overall performance of the website?

Imagine having an index.php file that includes multiple other files: Contents of index.php --------------------------- include('header.php'); include('footer.php'); --------------------------- Contents of header.php ------------------ ...

Expand the width of the div element to fill the entire space once the div is concealed

I have 3 different sections. By clicking on "HIDE" in the first section (divChaptersHide), it will be hidden to reveal another smaller section (divChaptersExpand). Then, by clicking on "EXPAND" in divChaptersExpand, it will hide that section and show divCh ...

Adaptable placement of background across screen widths

I am facing an issue with three buttons that have the same height and width, text, and background icons on the right. On small screens or when there is only a single word in the button, I want to move the icons to the bottom center of the button. Is there ...

Retrieving an array from PHP to JS through AJAX

I need assistance with modifying my code. When I click the "Add New" button in the data table, I want to replace the text boxes with a dropdown menu that retrieves values from a database. Here is my current code: // Function to add new row function addedi ...

What is the method for accessing cookies using JSONP?

Hello, I am trying to load a page from index.html using the following code: <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.2.min.js"></script> <script> function jsonCallback(json){ console.log(json); alert(document.c ...

Encountering the error "removeAttr is not a valid function" is causing some issues

Currently, I have integrated jquery-1.7.2.min.js into my project. An unexpected TypeError is arising: $("#TextBox1").removeattr is not a function [Break On This Error] $("#TextBox1").removeattr("disabled"); Can anyone shed some light on why this issu ...

Searching for values in an array using the $elemMatch operator in MongoDB 2.6 without the need for the $eq operator

Looking to retrieve all users with a specified objectId in an array. Here is the query I'm using: var query = { 'arrayOfIds': { $elemMatch: { $eq: id } }, }; This query functions well in mongodb 3.0. However, in mongodb 2.6, there isn& ...