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).

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:

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

Managing Import Structure in Turborepo/Typescript Package

I am currently working on creating a range of TypeScript packages as part of a Turborepo project. Here is an example of how the import structure for these packages looks like: import { Test } from "package-name" import { Test } from "package ...

When using `element.addEventListener`, event.target will be the target

When working on a solution, I initially bound event listeners to multiple targets within the same container. I am curious to know if anyone has noticed considerable performance improvements by using just one event listener and leveraging the target of the ...

ESLint warning: Potentially risky assignment of an undetermined data type and hazardous invocation of an undetermined data type value

Review this test code: import { isHtmlLinkDescriptor } from '@remix-run/react/links' import invariant from 'tiny-invariant' import { links } from '~/root' it('should return a rel=stylesheet', () => { const resp ...

Tips for emphasizing specific text within HTML tags without highlighting the tags in Vue

I am using a tag with v-html to render HTML text and display it, like so: <div v-html="htmlText"></div> I have written code to highlight text and it works on regular text: Vue.filter('highlight', function (word, query) { ...

Looking for assistance in setting a new initial state for a javascript toggle on page load

Need assistance with customizing the Youtube-TV JS plugin for a client website? The current setup loads the player with a playlist in an open state, but the requirement is to load it with the toggle closed, displaying the array of playlists instead. If y ...

utilizing a dynamic value within CSS modules for class naming

Struggling to incorporate a variable into a CSS module class name in Next.js. Finding it challenging to determine the correct syntax. The variable is fetched from the API: const type = red Here's how I'm attempting to achieve it: <div clas ...

Tips for choosing every <div> within a specific class

I'm trying to create multiple boxes within a class, all with the same background color. I've written code for 6 boxes in the "color-board" class, but when I go to select them, only 1 box is displaying... Below is the code for the class and how I ...

Variations between <div/> and <div></div>

When using Ajax to load two divs, I discovered an interesting difference in the way they are written. If I write them like this: <div id="informCandidacyId"/> <div id="idDivFiles"/> Although both divs are being loaded, only one view is added ...

Exploring ways to display dynamic content within AngularJs Tabs

I need help figuring out how to display unique data dynamically for each tab within a table with tabs. Can anyone assist me with this? https://i.stack.imgur.com/63H3L.png Below is the code snippet for the tabs: <md-tab ng-repe ...

What is the process for installing fontawesome using npm?

I encountered an error while attempting to install that looks like the following: $ npm install --save @fortawesome/fontawesome-free npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\Admin\Desktop\package.json&a ...

Establish the directive upon receiving the broadcast

Is there a way to trigger a directive when a specific event occurs on the backend and sets a value to false?... This is where the event is being captured .factory('AuthInterceptor', function($q, $injector, $rootScope) { return { ...

Deciphering HTML with the Eyes

So, I find myself in a bit of a bind trying to come up with a title for this question. I have stumbled upon some HTML files that seem so complex, they could only have been crafted by the one and only Lord Lucifer himself. These files contain segments like ...

Node.js is known for its ability to export both reference and pointer values

Having an issue with exporting my routing table from my express application. In the /bin/www.js file, there is a global variable representing the routing table: var routingTable = []; To create a simple route, new routing objects are pushed using the se ...

File is indicating a status of 200 ok, however it is not being displayed on the screen (node.js, expressjs)

I'm trying to display a video file in the browser and access it like an API on my front end. My goal is to have my front end call the video using a simple <video> tag. <video> <source ="video/randomfile.mov" type="video/mov"> < ...

JQuery Accordion SubMenu/Nested Feature malfunctioning

I have successfully implemented a JQuery Accordion on my website and it is functioning properly, opening and closing as expected. However, I am facing an issue when trying to add a submenu within the accordion. The submenu does not work as intended and lac ...

Tips for selectively executing a script based on whether the DIV is within the viewport

I have a created a script as shown below: jQuery(function($) { $('.count').countTo({ from: 0, to: '400', speed: '3000', refreshInterval: 50, onComplete: func ...

Sharing information between sibling modules

Currently, I am faced with the challenge of transmitting data between two sibling components within the following component structure. The goal is to pass data without changing the relationships between these components. I prefer not to alter the componen ...

Bootstrap dropdown malfunction

I am having trouble with my dropdown menu. The browser is cutting off the blue box in the dropdown area. I'm not sure if I need to add some CSS or make changes to the Bootstrap code to fix this issue. I haven't made any unusual modifications, jus ...

How can I show a title when redirecting a URL in VUE JS?

My current setup includes a navigation drawer component that changes the title based on the user's route. For example, when navigating to the home page (e.g. "/"), the title updates to "Home", and when navigating to the profile page (e.g. /profile), t ...

Error: Unable to access attributes of an undefined object (specifically 'headers') in the Next.js evaluation

I encountered an issue with next js TypeError: Cannot read properties of undefined (reading 'headers') at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:254:61) Snippet of the pro ...