What are the best techniques for resizing a bar graph column to perfectly and proportionally match its container size?

Creating a basic bar chart library using vanilla JS and jQuery is what I'm working on. The code below is functional:


var userData = {
'Black': 8,
'Latino': 6,
'Native': 4,
'Asian': 10,
'White': 12,
'Indian': 9,
'Other': 5
};

var addColumns = function(dataObject) {
  var values = Object.values(dataObject);

  var columnContainer = document.createElement("div");
  $(columnContainer).css({
    "display": "flex",
    "flex-direction": "row",
    "align-items": "flex-end",
    "position": "relative",
    "padding-top": "8px",
    "margin-left": "50px",
    "padding-bottom": "10px"
  });

 for (i = 0; i < values.length; i++) {
  var column = document.createElement("div");
  column.innerHTML = '<br>' + values[i];
  $(column).css({
    "margin-right": "30px",
    "width": "90px",
    "background-color": "#68b24a",
    "text-align": "center",
    "text-padding": "20px",
    "height": values[i] * 20 + "px",
    "z-index": "1"
  });
  $(mainContainer).append(columnContainer);
  $(columnContainer).append(column);
}

However, when dealing with large numbers like 400, 450, 430, or 500, the columns become oversized and require scrolling. My mathematical skills are limited. Is there a way to adjust the column height based on a percentage? Or perhaps scale the values down proportionally to fit the container size?

Answer №1

To establish a ratio, you can specify the maximum height as equal to the size of the container (let's say 150px) and then calculate the current value based on that.

20 : X = 500 : 150

In this equation, 20 represents the current element value, X is the variable being calculated, 500 stands for the maximum array value, and 150 indicates the maximum height supported in pixels.

Therefore, solving it would be: 500 * X = 150 * 20 => X = (150*20) / 500 which equals to 6 pixels.

You could also use percentages by substituting 100 for 150 and assuming that all values are relative (in percentage).

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

Error occurs when passing a service as a parameter to a controller in AngularJS

After adding 'loginService' as a parameter to the controller in order to reference the service I want to use, I encountered an error that caused the rest of my angular functions to stop working. app.controller('loginController', functi ...

"Exploring the world of Mean.js with Node.js background functionalities

Struggling with my mean.js app as I try to figure out how to implement background processes. I want these processes to run continuously, interacting with the mongodb database and handling tasks like cleanup, email notifications, and tweets. I need access ...

How can I reduce the number of pagination links in React js?

I need assistance in limiting the amount of pagination displayed on my website. Currently, I am fetching page numbers from the backend using Axios and useEffect, and then displaying them in JSX. However, I am struggling to limit the displayed numbers. Can ...

Transmit data to PHP servers

When the button in my HTML is clicked, it should trigger a query in a PHP file that will display the results. However, the button does not seem to be working as expected. What could be causing this issue? Here is the code I have tried: <?php $reply_ ...

In what way does s% access the title attribute within the Helmet component?

I am seeking clarification on how the reference to %s is connected to the title attribute of the <SEO /> component within the <Helmet /> component in the gatsby starter theme. Can you explain this? Link to GitHub repo On Line 19 of the code: ...

What is the best way to define ngOptionValue for my ng-option selection?

After updating my select/option code to include a search feature, it caused an issue with my function create. Here is the HTML code: <div class="input-group"> <label htmlFor="categoria" class="sr-only"> ...

modifying the source of an Ajax POST request

Is it possible to modify the referrer in an HTTP Ajax call using jQuery or JavaScript? I'm looking to send a request from my page but have the referrer appear as though it came from another page. Any insights would be appreciated. ...

Toggle the visibility of all elements using jQuery by creating multiple buttons for each action

I have a group of 4 buttons that control the visibility of images on the page. Each button toggles between showing and hiding all images when clicked. When a button is clicked, it changes its text from "HIDE ALL" to "DISPLAY ALL." The issue I'm facin ...

"Bringing in" ES6 for Node

I am interested in utilizing import from ES6 instead of require from common.js in Node. Surprisingly, I initially assumed that import would function automatically in Node. However, it appears that it does not. Is there a specific npm package that needs t ...

Shader material for border and overlay effects in THREE.js

Can a sphere in THREE.js be given a material shader to achieve a unique visual effect like the one shown here? (I'm specifically interested in replicating the border, glow, and streak on the red sphere.) https://i.sstatic.net/rjfkm.png If this is po ...

Exploring criteria in mongodb

user.js exports.searchProducts = async (productName, productBrand) => { let queryFilters = { productName, productBrand } // ====>>> if productBrand or productName is = '' then it does not search queryFilters = JSON.parse(JSON.stri ...

Maintaining the layout of blank lines in HTML content within JEditorPane

It has come to my attention that in an HTML JEditorPane, when there is an empty line, any previously applied styling disappears. Take a look at the code snippet below: import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.SwingUtil ...

Passing data from PHP to jQuery in a file upload script

I'm facing a problem that I can't seem to solve on my own. What I am trying to achieve is to upload a file to the server via PHP (upload.php), generate a new filename, and then pass that new filename to my webpage (upload.html). Within my uploa ...

At what point is it appropriate for me to delete the token?

Seeking Answers: Token Dilemmas Is it best to create the token upon user login and registration, or just on login? Should the token be saved in local storage? Do I need to send the token after every user request? Should the token o ...

What could be causing justify-content: flex-start; to not function as expected?

Can someone help me with my flexbox navbar? I set the justify-content property to flex-start, but the content inside the container is not aligning correctly. You can see the output and code here: output html, body { backgr ...

Ways to restrict input text to a specific set of values

When using an input text form, I need to ensure that users only insert values ranging from 1 to 10. However, my attempts to utilize a mask for customization have resulted in allowing values higher than 10. How can I restrict the input to only be allowed b ...

Looping through required fields in jQuery based on a CSS class

Is there a way to loop through required fields marked with <input class="required">? Currently, only the first input in the loop is being evaluated. How can I traverse the DOM using a loop to check all input boxes? Thank you for your help. While I ...

conceal or reveal a button based on the authentication status of a user in a

I'd like to display a "Become Tutor" button if either: 1. The user is not logged in. 2. The logged-in user is not already a tutor. Otherwise, I want to show the "Tutor Dashboard" button for users who are already tutors. While my code is functional, i ...

Switching classes in real time with JavaScript

I'm struggling to understand how to toggle a class based on the anchor text that is clicked. <div> <a id="Menu1" href="#">Menu</a> <div id="subMenu1" class="subLevel"> <p>stuff</p> </div> <div> <a i ...

Tips for breaking up array elements across multiple "tr" tags

In this particular example, I have a Fiddle set up with multiple tr elements displayed within an ng-repeat. My goal is to have three td elements per row. Would it be necessary to use an inner angularjs ng-repeat and split the iconDets array for this purpos ...