JS Issue with Generating Content

Introduction( kind of :) )

Starting with the process of generating 5 coffee beans for each cup of coffee. The coffee class includes a strength attribute, and my goal is to visually distinguish the coffee beans which have a strength greater than the selected value (as shown in the image below).

https://i.sstatic.net/D9TTg.jpg

My CoffeeMachine Class (simplified):

class CoffeeMachine {
    constructor() {
        this.name = ""
        this.coffeeList = { list: [] }
        this.tokenList = { list: [] }
        this.shoppingCard = { list: [] }
    }
    addCoffe(coffee) {
        this.coffeeList.list.push(coffee)
    }
    addToken(token) {
        this.coffeeList.list.push(token)
    }
    addToCart(item) {
        this.shoppingCard.list.push(item)
    }
}

My Coffee Class (simplified):

class Coffee {
    constructor() {
        this.name = ""
        this.price = 0
        this.time = 0.0
        this.imgsrc = ""
        this.strength = 0
        this.sugar = 0
        this.caffeine = 0
        this.values = []
        this.titelArray = ["caffeeine", "sugar", "time", "strength"]
        this.colors = ["#e34444", "#7944e3", "#44e35c", "#e3d044"]
    }
    setValues(name, price, time, strength, imgsrc, sugar, caffeine) {
        this.name = name
        this.price = price
        this.time = time
        this.strength = strength
        this.imgsrc = imgsrc
        this.sugar = sugar
        this.caffeine = caffeine
    }
    setCoffeeValues() {
        this.values = [this.caffeine + "mg", this.sugar + "g", this.time + "s", this.strength + "/5"]
    }

}

The coffees will be added to the shopping cart list in the coffee machine as shown below:

coffeeMachine.shoppingCard.list.push(coffeeMachine.coffeeList.list[index])

Initializing the coffees

coffeeLatte.setValues("Latte Macchiato", 1.60, 30.0, 3, "../pics/coffeeLatte.png", 18, 75)
        coffeeBlack.setValues("Black Coffee", 1.20, 20.0, 5, "../pics/coffeeBlack.png", 4, 95)
        coffeCappunchino.setValues("Cappuccino", 1.60, 35, 2, "../pics/coffeeCappuchino.png", 12, 64)

The update shopping cart method in the coffee machine class (the problem):

This is how I generate the beans for each coffee in the list:

  for (let i = 0; i < this.shoppingCard.list.length; i++) {
            for (let j = 0; j < 5; j++) {
                document.getElementsByClassName('beans')[i].innerHTML += `<img class="bean" src="../pics/bean.png"></img>`
            }
        }

In the code below, I adjust the opacity for the coffee beans based on their respective strengths:

for (let i = 0; i < this.shoppingCard.list.length; i++) {
    for (let j = 0; j < this.shoppingCard.list[i].strength; j++) {
        document.getElementsByClassName('bean')[i].style.opacity = "1"
        if (j <= this.shoppingCard.list[i].strength){
            for (let k = this.shoppingCard.list[i].strength; k < 5; k++) {
                document.getElementsByClassName('bean')[k].style.opacity = "0.3"

            }
        }
    }
}  

Upon adding multiple coffees to the shopping cart, the visualization appears as follows: https://i.sstatic.net/QV0wT.jpg

Answer №1

Perhaps this could provide a resolution to your issue

for (let j = 1; j <= this.shoppingCard.list[i]; j++) {
    for (let k = 0; k < 5; k++) {
        if (k + 1 < this.shoppingCard.list[i].strength) {
            document.getElementsByClassName('bean')[0].children[k].style.opacity = "1"
        } else {
            document.getElementsByClassName('bean')[0].children[k].style.opacity = "0.3"
        }
    }
}

Answer №2

Unclear about the purpose of all the loops, you might want to experiment with this alternative approach:

for (let x = 0; x < this.cart.items.length; x++) {
  let quality = this.cart.items[x].quality;
  for (let y = 0; y < 6; y++) {
    document.getElementsByClassName('product')[x * 6 + y].style.opacity = y <= quality ? "1" : "0.4";
  }
}

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

Aligning a tri-column design

I'm encountering an issue with this code that's preventing it from running properly on Google Chrome (I haven't tried other browsers). When the content displays, the regular paragraphs appear aligned to the far left instead of being centered ...

HTML control for adjusting the pan and tilt of a device

I'm looking to develop an interactive input where users can drag a dot within a box and see the 2D coordinates of that dot displayed. The goal is to use this feature to control pan and tilt values. A similar functionality from another application is s ...

Trouble with jquery/ajax form submission functionality

I followed a jQuery code for form submission that I found on various tutorial websites, but unfortunately, the ajax functionality doesn't seem to be working. When I try to submit the form, nothing happens at all. I've tried troubleshooting in eve ...

Looking to locate or track duplicate values within a multi-dimensional array?

In a multidimensional array, I am looking to detect and count duplicates. If duplicates are found, an alert should be triggered. Arr =[[2,"sk"],[3,"df"],[7,"uz"],[3,"df"],[7,"gh"]] Suggestions: One way to ...

Passing parameters as an array in Angular can be done by using the format: ?category[]=1&category[]=2&category[]=3,

Struggling to send an array using the $http.get() method in AngularJS. Here's my current approach: $http.get('/events.json', {params: {category_id: [1,2]}}); While I anticipate the request to be sent as /events.json?category_id[]=1&cat ...

Issue with bootstrap: the navbar highlight and anchor href are not functioning as intended

I'm currently working on creating a Navbar and implementing the navbar highlighting feature using the active bootstrap class. Below is the code I have tried: <!DOCTYPE html> <html lang="en"> <head> <!-- Bootstrap CSS ...

The intricacies of the leap search method

Can someone assist me in determining the complexity of the jump search algorithm? I apologize for the additional text required, please disregard it. I really need help with this. void jump_search(Pointeur_L1 P, int length, char * word) { Pointeur_L1 inf, ...

How can I effectively monitor and manage updates in my Vue app that is performing CRUD operations?

In my current project, I am developing a Vue application that utilizes Vuex to retrieve objects from an API. These objects are displayed in tables with paging functionality and are retrieved in batches from the API, sometimes containing nested entities. Th ...

Bootstrap5.2 is not functioning properly on mobile devices

While Bootstrap functions well on a PC and even in the mobile view on a PC, it seems to be malfunctioning when accessed on a phone directly. The bootstrap navbar and buttons are unresponsive on mobile devices. Check out how it looks on a PC: https://i.ss ...

Is it possible to combine two conditions using CSS?

Hello, I have a question about CSS. In my navigation bar, I have 3 links with different styles: #p1 { font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 45px; font-weight: bolder; color: #999999; text-dec ...

How to implement dynamic color for classes in a v-for loop using Vue.js?

Struggling with a seemingly simple issue that may be easy for VueJS pros. In my data, I have JSON objects with an attribute that can take values of 10, 20, 30, or 40. Depending on this value, I want to change the color of a v-btn. I've attempted mul ...

Is it possible for image.src to pose a security threat?

Here is the code snippet I am working with: var image = new Image(); image.src = "https://MyTrackingSite.com/?myTrackingParameter=whatever" I noticed that the image is not added to the DOM tree. Is it still rendered by the command "image.src"? Could this ...

What's the best way to iterate through multiple objects within <td> tags using Vue.js?

I have an Array filled with multiple Objects, and now I am interested in iterating through each object as a <tr> within a <table>. I have successfully achieved this. However, some of these objects might contain nested objects. In such cases, I ...

Importing a JavaScript file into another JavaScript file as text in React Native can be a convenient way

In my project, I have a file named MyFirstPage.js that contains the following code snippet: renderCards() { let icon = this.state.icon; .... .... .... } This code is responsible for rendering cards within the main render function. However, as the ...

Trouble aligning content in CSS? Try using justify-content center for perfect centering!

I am facing an issue with centralizing the content properly. Despite using justify-content:center, the layout breaks. When I apply justify-content:center, the layout appears like this: Here is the HTML / JSX code snippet: <div className={styles.co ...

Experimenting with the static method within a singleton class using Typescript and Sinon

I have a separate layer in my application that uses a DAO class to retrieve data from the repository. I've implemented the DAO class as a Singleton and made its methods static. In another class, I've created service methods to manipulate the dat ...

Adding some extra space inside a flex container using Bootstrap's padding

When attempting to use padding within a d-flex container to separate elements that are placed inline due to the d-flex class, I encountered an issue where the padding was not being applied and did not change anything. If I do not utilize the d-flex class, ...

Retrieving ng-pattern as a variable from a service

Hey there! I'm currently working on an application that requires extensive form validation across multiple pages. To streamline this process, I am attempting to extract validation patterns from a service used among the controllers. However, I've ...

Replace the ngOnDestroy method

Is there a way to complete an observable when the ngOnDestroy is triggered? I'd prefer not to create new child components when dealing with just one component instance. I attempted to override ngOnDestroy by modifying the function in the component&apo ...

Creating an object using JSON data?

Currently, I am in the process of creating a City class that will be populated with JSON data retrieved from a server. public class City { public string id { get; set; } public string country { get; set; } public string region { get; set; } ...