Using javascript to dynamically change text color depending on the selected item

I am currently working on a website for a snow cone stand and I want to incorporate an interactive feature using JavaScript. Specifically, I would like to color code the flavor list based on the actual fruit color. The flavor list is already structured in arrays and inserted into the HTML page using my addToPage function. Can anyone suggest how I can create an array of colors and implement this coloring functionality? Thank you.

var flavorAdder = (function() {

var flavorArr1, flavorArr2, flavorArr3, flavorArr4, textLocator1, textLocator2, textLocator3, textLocator4, addToPage;

flavorArr1 = [
    '<p>Apple</p>',
    '<p>Banana</p>',
    '<p>Birthday Cake</p>',
    '<p>Black Cherry</p>'
];

flavorArr2 = [
    '<p>Green Apple</p>',
    '<p>Guava</p>',
    '<p>Honeydew Melon</p>',
    '<p>Huckleberry</p>'
];

flavorArr3 = [
    '<p>Peach</p>',
    '<p>Piña Coloda</p>',
    '<p>Pineapple</p>',
    '<p>Pink Grapefruit</p>'
];

flavorArr4 = [
    '<p>Pink Lemonade</p>',
    '<p>Red Raspberry</p>',
    '<p>Rootbeer</p>'
];

textLocator1 = document.querySelector('#flavorList1');
textLocator2 = document.querySelector('#flavorList2');
textLocator3 = document.querySelector('#flavorList3');
textLocator4 = document.querySelector('#flavorList4');


addToPage = function(arr, text) {
    arr.forEach(function(current) {
        text.insertAdjacentHTML('beforeend', current);
    });
}

addToPage(flavorArr1, textLocator1);
addToPage(flavorArr2, textLocator2);
addToPage(flavorArr3, textLocator3);
addToPage(flavorArr4, textLocator4);


})();

Answer №1

To customize the appearance of the flavor array, you can assign css classes like so:

flavorArr1 = [
    '<p class="mint">Mint</p>',
    '<p class="lemon">Lemon</p>',
    '<p class="strawberry">Strawberry</p>',
    '<p class="blueberry">Blueberry</p>'
];

In a css/sass file, define the styles for each class:

.mint {
    color: green;
}

.blueberry {
    color: blue;
}
...

Answer №2

The simplest approach would involve adding specific classes and then styling each based on those classes.

arr1 = [
    '<p class="blue">Blueberry</p>',
    '<p class="orange">Orange</p>',
    '<p class="pink">Strawberry</p>',
    '<p class="purple">Grape</p>'
];

arr2 = [
    '<p class="teal">Watermelon</p>',
    '<p class="maroon">Cherry</p>',
    '<p class="gold">Pineapple</p>',
    '<p class="silver">Coconut</p>'
];

CSS: can be embedded or in a stylesheet

<style>
.blue{color:blue;}
.orange{color:orange;}
.pink{color:pink;}
.purple{color:purple;}
.teal{color:teal;}
.maroon{color:maroon;}
.gold{color:gold;}
.silver{color:silver;}
</style>

Answer №3

To modify the color using JavaScript, you can simply remove and add new classes:

var cherry = document.getElementById("cherry");
cherry.classList.remove("red");
cherry.classList.add("yellow");

CSS styles:

.yellow {
    color: yellow;
}
.red {
    color: red;
}

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

Is it possible to center-align the text in a Material-ui TextField and enforce a minimum numerical value at the same time?

I'm facing an issue with trying to center align the text inside the TextField and also set a minimum value of 0. It seems like I can only achieve one or the other, but not both simultaneously. I referred to the material-ui page on TextField for help, ...

Generating a business card example using node-html-pdf on an Ubuntu operating system

I am currently attempting to utilize the node-html-pdf module on Ubuntu 16.04 by following the businesscard example provided at https://github.com/marcbachmann/node-html-pdf. Regrettably, I encountered difficulties in generating the PDF file. To begin wi ...

Why is the div element within the container not automatically occupying 12 columns, but rather only 1?

I'm struggling to comprehend the bootstrap grid system, as explained in Murach's .Net book. Please take the time to read through the entire post. I am aware of the solution (<div class="col-lg-12">Col x</div> works), but I am curious ...

I have difficulty generating appropriate pseudonyms

Struggling to create aliases in my react project (CRA 3.1.1) has been a challenge for me. Despite attempting various methods, I have not been successful in achieving it. The only success I've had so far is aliasing the simple "src" folder based on som ...

Error: The script is not found in the package.json configuration

I encountered the following error while trying to execute npm run dev: Error: Missing script: "dev" Error: Error: To view a list of available scripts, use the command: Error: npm run Here is a list of scripts present in my package.json file: "scripts ...

Is there a way to extract an icon from an object or array?

Currently, I am facing challenges in extracting an icon from either an object or an array for a project I am working on. My approach involves storing the icon in a variable and passing it as a prop to another component. However, the functionality is not wo ...

The latest grid system in Bootstrap 5 is designed to streamline

I'm attempting to use Bootstrap 5 to create a grid system similar to the image shown below View Image I've been struggling to replicate the grid section shown in the attached image using Bootstrap 5. <div class="container-fluid"> ...

Which delivers better performance: HTTP request from server or client?

Considering the optimal performance, is there a difference in using Angular's HTTP request within a MEAN-stack environment compared to utilizing Request.js or similar for server requests? ...

Guide to removing a particular textfield from a table by clicking a button with ReactJS and Material UI

I need assistance with deleting a textfield on a specific row within a table when the delete button for that row is clicked. Currently, I am able to add a text field by clicking an add button and delete it by clicking a remove button. However, the issue is ...

Is it possible to upload multiple files using JavaScript?

My JavaScript project can be found on GitHub. You can check out a live demo of the project here. The main goal for my HTML Button with id='Multiple-Files' is to enable users to upload multiple files, have them displayed in the console, and then ...

Guide on adding up the value of a property within an array of objects using AngularJS

I am receiving an array of results from a Node.js API in my Angular app, and here is how it looks: <div *ngFor="let result of results"> <div *ngIf="result.harmattan.length > 0"> ... </div> <br> .. ...

VS Code sees JavaScript files as if they were Typescript

I have recently delved into the world of Typescript and have been using it for a few days now. Everything seems to be working smoothly - Emmet, linting, etc. However, I've encountered an issue when trying to open my older JavaScript projects in VS Cod ...

Comparison of passwords in Nodejs is hindered by Bcryptjs

Struggling to compare passwords using bcryptjs for JWT authentication. Unable to successfully verify the password during login to sign the token and send it to the client. Issue The problem arises when trying to use the .compare() method in bcryptjs and ...

Exporting a function to another class using the default export is a common practice

I'm working with two classes, Orders.js and api.js. In api.js, I need to invoke a function called ShowAlertWithDelay. However, due to the existence of a default export named mapStateToProps, I am unable to declare another export. Below is the code sni ...

Unusual hue in the backdrop of a daisyui modal

https://i.stack.imgur.com/fLQdY.png I have tried various methods, but I am unable to get rid of the strange color in the background of the Modal. Just for reference, I am using Tailwind CSS with Daisy UI on Next.JS. <> <button className='btn ...

Encountering Difficulty Fetching Data from JSON File Utilizing AngularJS

insert image description hereI am struggling to fetch data from a Json file using Angular Js. I am attempting to retrieve the Json data from a URL by clicking a button in Angular Js, and also add an empty tr td in a table when the button is clicked. ...

The Javascript function will only initiate upon a manual reload of the page

My function is working perfectly, but only after I reload the page once it has been loaded. This function is a timer that starts counting down from 10 to 0 as soon as the page loads (which is the intended behavior). However, when I first land on the page ...

Verifying the angular form without the need for a submit button

I'm currently utilizing angular.js form validation and I'm looking to implement validation without the use of a form submit button. Below is my HTML code: <form name="userForm"> <input type="hidden" ng-model="StandardID" /> < ...

Issue with ForwardRef component in Jest for React Native testing

When attempting to write a test case for my Post Detail screen, I encountered an error that stated: error occurred in the <ForwardRef> component: Here is my test class code: import React from "react"; import { NewPostScreenTemplate } from ...

Bootstrap 4 alert boxes extend the text to span the entire width of the alert

How can I make the paragraph text span across most of the box width in Bootstrap 4? <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJ ...