Adjusting the width of bars using JavaScript

Can anyone assist me with adjusting the width of bars in a horizontal bar graph based on percentage data? Check out my code on jsfiddle here

Thank you in advance!

var data = {
    "box1": {
        "bar1": "80%",
        "bar2": "60%",
        "bar3": "40%",
        "bar4": "50%",
        "total": "60%",
    },
};

$(document).ready(function() {
    $(".score-text").html(data.box1.total);
    $(".data").text(data.box1.bar1);
    $(".data").text(data.box1.bar2);
    $(".data").text(data.box1.bar3);
    $(".data").text(data.box1.bar4);
});

    
body {
background: #efefef;
width: 100%;
margin: 0px;
text-align: center;
}

h2 {
font-family: 'Noto Sans', serif;
color: #b71f38;
font-weight: 300;
margin: 0px;
}

h3 {
font-family: 'Noto Sans', serif;
color: #444444;
font-weight: 200;
margin: 0px;
}

#colLeft {
width: 50%;
float: left;
}

#colRight {
width: 50%;
float: right;
}

#row {
background: #e2e2e2;
width: auto;
height: 230px;
margin: 15px;
border-radius: 5px;
}

#insideColLeft {
width: 30%;
float: left;
}

#insideColRight {
width: 69%;
float: right;
padding-top: 8px;
padding-right: 5px;
}

.circle {
margin-left: auto;
margin-right: auto;
border-radius: 50%;
width: 150px;
position: relative;
background: #b71f38;
}

.circle:before {
content: "";
display: block;
padding-top: 100%;
}

.circle-inner {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
text-align: center;
}

.score-text {
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
height: 1em;
line-height: 1em;
font-size: 30px;
font-family: 'Fjalla One', sans-serif;
color: #ffffff;
}

.date {
font-family: 'Fjalla One', sans-serif;
text-align: center;
color: #333333;
}

ul.graph {
margin: 0;
padding: 0;
list-style-type: none;
}

ul.graph li {
margin: 10px;
height: 25px;
background: #ccc;
color: #fff;
}

ul.graph li.data {
background: #f4ebb8;
}
<div id="row">
      <h2>Title</h2>
      <h3>Subtitle</h3>
      <div id="insideColLeft">
        <div class="circle">
          <div class="circle-inner">
            <div class="score-text">
            </div>
          </div>
        </div>
        
      </div>
      <div id="insideColRight">
        <ul class="graph">
          <li class="data">bar 1</li>
          <li class="data">bar 2</li>
          <li class="data">bar 3</li>
          <li class="data">bar 4</li>
        </ul>
      </div>
    </div>

If I have multiple datasets, how can I create a loop to iterate through each one? Also, if I want to load data from a local CSV file, check out the updated js fiddle here

Answer №1

Check out this example: http://jsfiddle.net/kmc3ohab/5/

$(document).ready(function() {
    $(".score-text").html(data.box1.total);
    $(".data").each(function( index, value ) {
        width = eval('data.box1.bar' + (index+1));
        value.innerText = width;
        value.style.width = width;
    });
});

The simple solution to your problem was adjusting the style.width for each bar element. I also expanded on your idea by:

  • Performing all actions in a loop. It would be more efficient to store bar values in an array instead of using eval().
  • Correctly setting both the text and width of the bar within the loop.

Edit for your new question regarding multiple sections of bars.

Displaying multiple sections depends on how you handle reading the csv file. Ideally, data should be stored in arrays and structured like this after being processed:

var data =
[
    {
        title: "Title 1",
        subTitle: "SubTitle 1",
        bars :
        [
           { name: "bar1", value: "80%" },
           { name: "bar2", value: "40%" },
           { name: "bar3", value: "50%" },
           { name: "bar4", value: "60%" }
        ],
        total: "60%"
    },
    {
        title: "Title 2",
        subTitle: "SubTitle 2",
        bars :
        [
           { name: "bar1", value: "80%" },
           { name: "bar2", value: "60%" },
           { name: "bar3", value: "40%" },
           { name: "bar4", value: "50%" }
        ],
        total: "80%"
    }
];

You can iterate over the section list as follows:

data.foreach(function(item) {
    ...
});

However, the crucial aspect is how you plan to generate HTML. Will you use document.write()? If the data quantity varies and HTML needs to be generated dynamically, setting properties while creating the HTML may simplify the process. Using AngularJS with ng-repeat might be advantageous here for defining HTML sections once. Considering you mentioned reading a local csv file, which implies non-server hosted HTML, incorporating Angular through CDNs could still be viable.

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

Simple steps to emphasize a table cell in Angular 2

Essentially, I have a table structured as shown below <table> <tr> <td>Date</td> <td>Time</td> <tr> <table> The goal is to make both the date and time clickable within this table. When clicking on the date, ...

React Project Encountering Issues with NPM Run Watch

Hey there! I'm currently trying to use NPM Run Watch in order to view localhost:3000 for my React Project, but I've encountered a strange error that has left me unsure of where to even start troubleshooting. Rubens-iMac:react-redux rubenesquiv ...

A div with 100% height is causing scrollbars to be positioned 50px off the screen due to a margin-top of 50px

Can someone help me with laying out a page that includes a horizontal navigation bar at the top and a content area that will display scrollbars if necessary? I've been trying to achieve this by using two divs - one for the navigation bar with dimensi ...

Safari alters the header color on mobile devices

Debugging this issue has been quite challenging - the number at the top of the page appears in white before changing to a dark grey on iPad and iPhones running Safari. Why is this happening?! It functions correctly on all other devices! Check out www.col ...

Verify whether all of the iframes have finished loading

I am facing an issue with running a function when multiple iframes on the page are loaded using jQuery. The function works fine when there is only one iframe, but as soon as there are more than one, it stops working. Below is the code I am currently using: ...

Having trouble uploading an image URL into a Vue component?

I'm currently facing an issue while creating a Vue tag component, as I am unable to pass the source to the template html <card aposter="assets\images\poster.png" aname="a title"> </card> JavaScript Vue ...

A guide to adding a picture to AWS S3 with the help of GraphQL

When trying to upload a base64 string via GraphQL, I encountered an issue. It seems that if the string exceeds 50,000 characters, GraphQL fails to reach the resolve function without giving any error messages. However, when the string is less than 50,000 ...

Sum values in project pipeline based on conditions with Mongo

I am currently implementing a project pipeline that involves filtering values greater than 100 from fields within an object that is part of an array. Here's an example of the database structure: Database: ---Clients Collection--- client: { _id: ...

Creating a form using Ajax in PHP to submit messages without having to refresh the page

I am trying to submit a form using an ajax call without having to refresh the page. Below is the HTML markup: <form id="form"> <input type="radio" name="radio" value="radio1"> <input type="radio" name="radio" value="radio1"> <input ...

Leveraging javascript to extract data from several input fields and dynamically incorporate them into a table

I'm currently in the process of developing a script that extracts field values and organizes them into a table for verification purposes. The challenge I face is that users have the ability to add multiple fields (up to 5), each with its own unique id ...

Add opening and closing HTML tags to enclose an already existing HTML structure

Is there a way to dynamically wrap the p tag inside a div with the class .description-wrapper using JavaScript or jQuery? This is the current html structure: <div class="coursePrerequisites"> <p> Lorem ipsum.. </p> </ ...

Set the gap size of the divider in a Square Grid Image using HTML

I need help adjusting the white space gap between my First Column and Second Column in a square grid. They currently appear too far apart, and I would like to specify exact measurements for this gap while keeping the pictures in a square shape. Additionall ...

Retrieve JSON information by utilizing variable string interpolation

Why is it that when I try to access an integer stored under id's/keys in a JSON object, the code doesn't work on its own? var rooms = { 'kitchen': [7, 40, 36, 16], 'livingroom': 31, 'livingroom2': 15, ...

The integration of cypress-cucumber-preprocessor with multiple testing frameworks appears to be experiencing compatibility issues

I am trying to set up a connection between Cypress and Cucumber, and I came across this plugin: https://www.npmjs.com/package/cypress-cucumber-preprocessor However, I am having trouble with my implementation as it seems to be missing. I have also added th ...

What are the steps for deploying a static Nuxtjs site to Hostgator or a different shared hosting provider?

I'm trying to figure out how to deploy a Nuxtjs static site on a shared hosting provider like hostgator. I initially thought that uploading the dist folder and pointing to the index.html file would be sufficient, but it seems like you need to keep the ...

Issue with checkboxes preventing submission of form

Currently working on a website project for a company that requires certain steps to be completed for deliveries. Unfortunately, I am facing issues with the submit button, and I apologize as I am still new to this. The code I have pasted is divided into tw ...

Error: Unable to locate module: 'fs' in Next.js

import nookies from 'nookies'; import { firebaseAdmin } from "../firebaseAdmin"; import { TChildren } from "../types/app/app.types"; interface Props { children: TChildren; } export default function ProtectedRoute(props ...

Prevent the user from being redirected to the login page again after they have already logged in, even if they attempt to go back using the browser's back button

I am in the process of building a login page that checks certain conditions and redirects the user to the home page. However, I want to implement a feature where once the user has visited the home page, they cannot go back to the login page by clicking the ...

Responsive Slider

In the current project I'm working on, I'm creating a team page that features a slider element. Originally, my goal was to replicate the functionality of the slick library without importing slick, jQuery, and also improve my JavaScript skills. ...

Angular2 - Error: The view has been destroyed and cannot be updated: detectChanges

My application keeps encountering this persistent error: extensions::uncaught_exception_handler:8 Error in event handler for runtime.onMessage: Attempt to use a destroyed view: detectChanges at ViewDestroyedException.BaseException [as constructor] (chrome ...