Iterating through elements to set the width of a container

I am currently working on a function that dynamically adjusts the width of an element using JavaScript. Here is my JavaScript code:

<script>
    $('.progress-fill span').each(function(){
        var percent = $(this).html();
        if(percent ==12){
          $(this).parent().css({
            'width' : "100%"
          });
        }
        if(percent ==11){
          $(this).parent().css({
            'width' : "92%"
          });
        }
        if(percent ==10){
          $(this).parent().css({
            'width' : "83%"
          });
        }
        if(percent == 9){
          $(this).parent().css({
            'width' : "75%"
          });
        }
    });
</script>

The HTML structure I am working with looks as follows:

<div class="results-block">
  <div class="progress-bar">
    <div class="progress-fill">
      <span>12</span>
    </div>
  </div>
</div>

Essentially, I am fetching the value from the .progress-fill span and based on this value, setting the width of the parent div accordingly. Currently, I have implemented separate if statements to handle this operation, however, I believe there might be a more efficient way to achieve this. Any alternative suggestions on how to approach this would be greatly appreciated!

Answer №1

To easily achieve this, one can calculate the width based on a percentage of the 12 potential values. Here is an example:

$('.progress-fill').css('width', function() {
  return 100 / 12 * $(this).find('span').text() + '%';
});
.progress-fill {
  background-color: #C00;
  color: #FFF;
  margin: 5px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="results-block">
  <div class="progress-bar">
    <div class="progress-fill">
      <span>12</span>
    </div>

    <div class="progress-fill">
      <span>6</span>
    </div>

    <div class="progress-fill">
      <span>10</span>
    </div>
  </div>
</div>

Answer №2

If you comprehend the question, there is an opportunity to calculate it. The minimum value is 1, which is equivalent to width: 0%, and the maximum value is 12, so it corresponds to width: 100%

<script>
    $('.progress-fill span').each(function(){
        var percentage = $(this).html();
        $(this).parent().css({
        'width' : "" + ((percentage - 1) * 100) / (12 - 1) + '%'
        });
    });
</script>

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

Discovering the art of line breaks

Imagine I have a random block of text displayed in a single line, like this: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Due to various reasons such as width settings or text-zoom, the text may display as two or more lines on the viewer&apos ...

Leveraging AngularJS for retrieving the total number of elements in a specific sub array

I'm currently working on a to-do list application using Angular. My goal is to show the number of items marked as done from an array object of Lists. Each List contains a collection of to-dos, which are structured like this: [{listName: "ESSENTIALS", ...

Having issues with the Email type in the JQuery Validation Plugin?

Recently, I set up a Grunt file to consolidate all my libraries and code into a single JS file for inclusion in my website. However, after adding the JQuery Validate plugin (http://jqueryvalidation.org/), I noticed that it's not working as expected. I ...

Is there a jQuery carousel that reloads the page with each slide?

I'm really interested in creating a slideshow similar to the one showcased here: My goal is for each slide to have its own unique URL/page, and for the page to refresh with every new slide. Could someone please shed some light on how this can be acc ...

The overflow:hidden feature is ineffective in Firefox, yet functions properly in both IE and Chrome browsers

I'm in the process of creating a webshop and facing an issue with my sidebar due to varying product counts on different pages. For now, I have implemented the following workaround: padding-bottom: 5000px; margin-bottom: -5000px; overflow: ...

Can you explain the distinction between ng-init and ng-bind?

Here is a code snippet utilizing ng-init: <!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body> <div ng-app="" ng-init="names=['Jani','Heg ...

What causes certain webpack / Babel ES6 imports without a specified extension to resolve as "undefined"?

When I try to import certain ES6 files (such as .js, .jsx, .ts, .tsx) using the syntax import ComponentName from './folder/ComponentName'; (without extension), they end up resolving as undefined. This occurs even though there are no errors from W ...

Invoking a function within the directive's controller

How can I access and call the method defined within the directive controller externally? <div ng-controller="MyCtrl"> <map></map> <button ng-click="updateMap()">call updateMap()</button> </div> app.directive(&a ...

What steps can we take to create a personalized PDF editor incorporating our unique edit functionalities using Vue.js?

Is it possible to create a PDF editor similar to MS Word using vuejs? How can I implement custom logic in the PDF editor with vuejs? For example, the features should include: Conditional replacement of text Adding tags to text within the PDF Changing the ...

What is the best way to pass and save information across different routes in Express using Node.js?

Let's delve into the specific functionalities I envision for my server. Essentially, my project involves user registration and login processes. The URLs for these routes are as follows - localhost:3000/login and localhost:3000/register Upon successf ...

Creating a dynamic tbody element on button click with the help of javascript or jquery

I am working with the following code: $(document).ready(function() { //Optimizing by selecting tbody first using jquery children var tbody = $('#myTable').children('tbody'); //If no tbody found, select the table itself ...

Is there a way to completely clear a form using jQuery in JavaScript?

I have a functioning script that sends emails via Ajax and PHP. However, I am also looking to reset the form after sending an email. Below is my jQuery code: <script src="http://code.jquery.com/jquery-latest.js"></script> <script> $(doc ...

Can you determine the sequence in which these code statements are placed on the call stack?

I am a beginner in the world of Javascript and currently seeking to grasp a better understanding of how the JS execution engine operates. I am aware that any asynchronous code statement is pushed onto the call stack and then promptly removed, allowing it t ...

Conceal a different div unless it includes

Hi everyone, I need help with a filter code snippet: $(".title").not(":contains('" + $("[name=filter]").val() + "')").hide() The issue I'm facing is that the .title class is nested within the .sortAll class along with many other divs. I w ...

What is the best way to transform Adobe XD designs into HTML and CSS with Vue.js?

I am looking to create a single page application with vue.js and came across this helpful reference at . A colleague has created a prototype using Adobe XD, and now my task is to transform it into HTML/CSS while making it functional and connecting it to an ...

Assignment on Ionic's Cascading Style Sheets classes

As I work on styling my app, I find myself struggling with the extra CSS classes that are added when I preview the source in a running app. It's particularly confusing when all I want to do is change the menu header background. In my app.html file, I ...

Issue with authentication when accessing Google Video API

I'm attempting to utilize the Google API provided: I have downloaded the Sample Project and followed these steps: 1) Navigate to the Project Folder named API Video 2) Run npm install 3) Set GCLOUD_PROJECT = neorisvideo 4) Download Json from the C ...

The JSON URL and how to handle the jQuery AJAX response

{ "imgsrc":"http:\/\/192.168.1.181\/postcardthis\/facebook\/angel_wall.jpg", "message":"asdf", "friend":"Friend1", "error_message":"" } This is my JSON data. I've noticed that the imgsrc location has double sl ...

Update data in PHP dynamically without reloading the page

It would be great if they are doing well! I have encountered a minor issue - everything seems to work perfectly, but it doesn't quite meet my requirements. I am referring to this particular function: <script> var previous = null; var current = ...

Importing Laravel select2 library is necessary for enhancing user experience and improving

I've been attempting to incorporate select2 into my project without success. Every time I try these two methods, I always receive an error saying $('#state').select2 is not a function. However, when I include select2 in a standard <scrip ...