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

Tips on using the .map() method to extract data from a JSON response received from a get request and utilizing the content within a specific index to populate table rows

Here is the JSON response representation, https://i.stack.imgur.com/0QWkv.png This is how my project displays it: https://i.stack.imgur.com/LnA5v.png The rendering code snippet is as follows: render() { const { materials } = this.state; ...

Traversing a hierarchical structure and building a REACT user interface based on it

Currently, I am tasked with a project that involves working with a hierarchy tree. The goal is to loop through the data provided by the tree and create a user-friendly UI representation of the hierarchy for seamless navigation. Here's an illustration ...

The blur filter in Safari causes colors to appear distorted

I am having an issue trying to add a blur filter to an SVG element. It appears that Safari is not rendering the colors correctly. Take a look at this example: <svg height="110" width="110"> <defs> <filter id="f1" x="0" y="0"&g ...

When Vue 3 is paired with Vite, it may result in a blank page being rendered if the

Issue with Rendering Counter in Vite Project After setting up a new project using Vite on an Arch-based operating system, I encountered a problem when attempting to create the simple counter from the Vue documentation. The element does not render as expec ...

Plotly Express Unleashes the Power of Subplots

After spending countless hours scouring the internet, I am feeling utterly frustrated and perplexed about how to deal with subplots using plotly express in Python. The concept is to create a line plot alongside a scatter plot and another line plot, where ...

Best Practices for Retrieving Data with Django - Post Requests

I'm attempting to use Ajax to send a JavaScript array to Django. Here's my code: document.getElementById('input-generate').onclick = () => { // Get the token const csrftoken = document.querySelector('[name=csrfmiddlewar ...

How to minimize the amount of typing needed when specifying grid positions in CSS Grid layout?

(I am currently in the process of upgrading the design of this data entry page from a basic CSS/HTML table layout to something more advanced, utilizing CSS Grid layout). Following common conventions, I have structured it into 12 columns. Each entry field ...

Designing an image transformation page by segmenting the image into fragments

Does anyone have insight into the creation process of websites like this one? Are there any plugins or tools that can assist in building something similar? ...

Deactivate the button while you wait for the Google Maps directionService

When utilizing the Google Maps service to plot a route with multiple waypoints and under slow 3G conditions, I need to deactivate an HTML button until the new route is traced. calculateRoad(departure: any, arrival: any) { const request = { origin: ...

An error was encountered when trying to read property '0' of an undefined object in a for loop

Currently, I am working on a project to create a mastermind game. Everything is progressing smoothly, except for one issue that keeps popping up - I keep encountering the error: "uncaught typeerror cannot read property '0' of undefined." fun ...

Protractor is able to achieve successful test results without actually executing the tests

SYMPTOMS When running Protractor, the tests pass successfully, but the pages do not load. Instead, they appear blank with "data:text/html" in the address bar (refer to the screenshot). Although the tests show as passed, there are 0 assertions being made. ...

Tips for concealing a parent element while inside a span with jquery

Beginner asking for help! Take a look at what I've coded: <div class="Links"> <a href="/testthis1.html" data-id="button1"> <img class="icon" src="/test1.png" alt="test1"> <span>Test 1</span> < ...

Tips for simultaneously updating a value in multiple collections on firestore?

Currently, I am in the process of developing a forum application using Vue, which is essentially a replica of this platform. In this app, users can post questions, receive answers to those questions, and leave comments on those answers. Each question, answ ...

Screen readers are unable to "read" text that is identified through aria-describedby

When enhancing my web application for accessibility, I encountered a challenge. I have implemented two required fields in a form that should display separate error messages as spans. To accomplish this, I am utilizing aria-invalid to signal when the fields ...

Selecting options in combobox for each row in a table using Angular 2 programmatically

I am currently working on an Angular 2 application using TypeScript. In one of the tables within the application, there is a select control in one of the columns. The contents of this select control are bound to another string array. <table ngContr ...

NextJS displays outcomes as per query parameters obtained from an external API

I have set up my NextJS app to connect to a rest API. The API returns results based on different filters in the query string, such as: /jobs /jobs?filter=completed /jobs?filter=upcoming /jobs?filter=cancelled On my NextJS page, I have a few buttons that I ...

Target the most recently loaded Vue.js element using jQuery's focus method

Hey there, I am currently utilizing Vue.js to load some data and below is the code snippet: add_line:function() { index = this.lines.length; this.lines.push({id:index}); $('.search_and_select').last().focus(); ...

Display various React components for widgets

I am looking to display multiple instances of a widget in html. I have 3 divs with the same id, each with different attributes, and I want to render my react component three times on the page. Currently, I am only able to display the first component. Here ...

What is the best way to toggle the visibility of the answers to a question when the corresponding hyperlink is clicked, and how can the text on this hyperlink be updated dynamically using jQuery?

I am currently working on a website using PHP, Smarty, and jQuery. On this website, I have a page that features a list of questions along with their available answer options and the correct answer. This page is dynamically generated using the "Smarty Tem ...

Tips on how to connect with ngFor

I have been working on an application to display various events, but I am encountering an issue. Whenever I load the webpage, it appears empty and the console throws an error saying 'Can't bind to 'ngForEvent' since it isn't a know ...