Use a boolean value to determine the styling of multiple items simultaneously

I'm currently attempting to modify the appearance of the bars in each area (a total of 12), so that a value of 1 equates to true (displayed as green) and a value of 0 equates to false (displayed as red). This will dynamically change the color of each bar based on the data received from the back-end.

I'm struggling to determine the most effective approach for achieving this.

Here's my current progress:

function createPeg(name, checkActive ){

  const uiProgressBar = document.querySelector(`.${name}-bar-fill`);


}

const allPegs = [
  createPeg('peg-1', pegActive["one"] == 0),
  createPeg('peg-2', pegActive["two"] == 1),
  createPeg('peg-3', pegActive["three"] == 1),
  createPeg('peg-4', pegActive["four"] == 1),
  createPeg('peg-5', pegActive["five"] == 1),
  createPeg('peg-6', pegActive["six"] == 1),
  createPeg('peg-7', pegActive["seven"] == 1),
  createPeg('peg-8', pegActive["eight"] == 1),
  createPeg('peg-9', pegActive["nine"] == 0),
  createPeg('peg-10', pegActive["ten"] == 1),
  createPeg('peg-11', pegActive["eleven"] == 1),
  createPeg('peg-12', pegActive["twelve"] == 1),
];

for(let i=0; i<allPegs.length; i++){
    if(allPegs[i] == 1){
        uiProgressBar.style.background = "green";
    } else if(allPegs[i] == 0){
        uiProgressBar.style.background = "red";
    }
    //to test is working
    else{
        uiProgressBar.style.background = "blue";
    }
}

CSS:

.peg-1-bar-fill {
  border-radius: 50px;
  height: 100%;
  width: 100%;
  max-width: 400px;
}

HTML:

<div class="peg-wrapper">
  <div class="peg-name-1">
          <h4>1</h4>
        </div>
        <div class="peg-1-start-time total-time">
          <p class="label-2">Length:</p>
          <span id="total-time-1">-</span>
        </div>
        <div class="peg-1-bar">
          <div class="peg-1-bar-fill">
          </div>
        </div>
         </div>

Answer №1

Why not consider using a ternary operator? These operators provide a succinct way to handle simple if statements.

foo === bar ? executeIfTrue() : executeIfFalse();

You can potentially assign class names dynamically inline using ternary operators.

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

Display a pop-up window using window.open and automatically print its contents using window.print upon loading

I am trying to open a new window with some HTML content and then automatically print it. Here is the code snippet I have: var windowObject = window.open('','windowObject','arguments...'); windowObject.document.write("<html ...

Working through JSON arrays in JavaScript

Here is a JSON example: var user = {"id": "1", "name": "Emily"} If I select "Emily," how can I retrieve the value "1"? I attempted the following code snippet: for (key in user) { if (user.hasOwnProperty(key)) { console.log(key + " = " + use ...

Discovering hidden files within appsettings.json in ASP.NET Core 6 using Program.cs

Within Appsettings.json, the code resembles the following: { "Project": { "ConnectionString": "Data Source=(local)\SQLSERVER; Database=MyCompany; Persist Security Info=false; User ID='sa'; Password='sa ...

React-router causing issues with Redux integration

Currently, I'm utilizing the following libraries: react v16.2.0, react-redux v5.0.7, react-router-dom v4.2.2, redux v3.7.2 The main goal is to update some properties within the Auth component and have these changes reflected when the user visits the ...

Designing Forms with Label Placement above Input Fields

I am working on creating a form with the following layout: <form name="message" method="post"> <section> <label for="name">Name</label> <input id="name" type="text" value="" name="name"> <label for="email"& ...

Instructions for creating a JavaScript click function that iterates through all records, not just the initial record

Although I'm new to web development and still learning the basics of html, javascript, etc., I have a problem that seems quite simple. The challenge lies in understanding javascript functions, which I find particularly tough to grasp. Here's what ...

Explain the concept of render hijacking in react technology

After learning about High Order Components (HOC), I came across the concept of render hijacking. Can someone please explain what exactly render hijacking entails? ...

Struggling to forward JSON data via AJAX to Django without relying on jQuery

My goal is to utilize AJAX in conjunction with Django, but I want to achieve this without relying on jQuery. So far, I have made progress in sending URL encoded data from AJAX to Django successfully. However, I am currently facing an issue where I am unabl ...

Top method for displaying and concealing GUI elements upon a click event

I would like a dat.GUI() instance to appear when a mesh is clicked, and disappear when it is clicked again. Furthermore, if it is clicked once more, I want it to reappear. Despite trying various approaches, I have been unable to achieve the desired behavio ...

Retrieving a MongoDB collection using its unique ID

Here's a query that may seem straightforward. I have two collections in MongoDB - one named "users" with an objectId, and the other named "listings" which has the userId. I am looking to retrieve documents from the listings collection by searching fo ...

"Sweet syntax" for assigning object property if the value is true

In the project I'm working on, I find myself dealing with a lot of parsing and validating tasks. This often results in 5-10+ lines of code like if(value) object.value = value. I considered using object.value = value || (your favorite falsy value) app ...

Is it possible to use uglifyjs to merge multiple files into a single minified file?

I attempted to compress multiple javascript files into one using the uglifyjs tool, but encountered an issue. I ran $node uglifyjs.js to execute the file. Below is the content of the uglify.js file: var fs = require('fs'); var uglifyjs = re ...

Transforming the shopping cart with redux-saga

Hey there! I've been working on implementing a shopping cart feature using redux-saga. The current code seems to be functioning properly, but I have some concerns about the way I'm handling the cart state. It looks like I might be mutating the ca ...

Verify whether all the elements within a specific div are distinct by utilizing jQuery

I need to create a select box that, when an option is chosen, generates a certain number of textboxes within a div. Currently, there are three fields: display_name[], user_name[], and user_password[] The code for this functionality is as follows: <se ...

Transmit information using jQuery to an MVC controller

I am developing an ASP.NET MVC3 application and need to send three pieces of data to a specific action when the user clicks on an anchor tag: <a onclick='sendData(<#= Data1,Data2,Data3 #>)'></a> Here is the javascript function ...

Using CSS files in the web directory in CakePHP and connecting them to HTML

Could someone offer some help with cakephp? I'm experiencing an issue related to routes that I can't seem to resolve. I've organized all my css files in webroot/css within my app. In my default layout, I included a html link <link href=" ...

Is there a way to access an HTML element using Vue's methods?

Here is an example of my Vue component structure: <template> ... </template> <script> export default { methods: { buildDescription () { if (!this.description) { const div = document.createEl ...

Leveraging Three.js Raycaster for a seamless PDF download functionality

Is there a way to trigger a PDF download when clicking on a 3D object in a Three.js scene? Below is an example of how I have set up the Raycaster: var raycaster; var mouse = { x: 0, y: 0 }; init(); function init() { raycaster = new THREE.Raycaster() ...

The functionality of ngModel is not functioning properly on a modal page within Ionic version 6

Currently I am working on an Ionic/Angular application and I have encountered a situation where I am attempting to utilize ngModel. Essentially, I am trying to implement the following functionality within my app: <ion-list> <ion-item> <ion ...

How can we organize and display the data from two linked arrays, one containing player names and the other containing

Looking for help on how to rank 3 players based on their scores using arrays. I've hit a roadblock and need guidance! Here's a brief example: Player 1 : Taylor Score Taylor : 15 Player 2 : Jordan Score Jordan : 20 Player 3 : Alex Score Alex : ...