Utilize JavaScript to assign a unique color to each category

I'm currently working on a JavaScript task

My goal is to assign specific colors to different categories

For example: if category name = x then color = blue if category name = y then color = red ...

I attempted the following code, but it seems like I might be missing something:

categories.forEach(category => {
            if (category.attributes.slug === "animation") {
                cat.style.color = animColor;
            }
            if (category.attributes.slug === "decor") {
                cat.style.color = decorColor;
            }
            if (category.attributes.slug === "illustrations") {
                cat.style.color = illuColor;
            }
            if (category.attributes.slug === "developpement-visuel") {
                cat.style.color = devVisuel;
            }
            if (category.attributes.slug === "realisations") {
                cat.style.color = real;
            }
            if (category.attributes.slug === "croquis") {
                cat.style.color = croquis;
            }
        });


   <div>
            <Header
                categories={categories}
                homepage={homepage} />
            <div className="hidden md:block px-5 pt-10">
                <a className="hover:no-underline " href="/">
                    <h3 className="text-xl uppercase tracking-widest mb-4">{homepage.attributes.hero.title}</h3>
                </a>
                <h5 className="text-sm mb-10">{homepage.attributes.bio.text}</h5>
                <nav>
                    <ul>
                        {categories.map((category) => {
                            return (
                                <li key={category.id} className="mb-4">
                                    <Link href={`/category/${category.attributes.slug}`}>
                                        <a id="cat" className="uppercase font-light text-sm">{category.attributes.name}</a>
                                    </Link>
                                </li>
                            )
                        })}
                    </ul>
                </nav>
            </div>
        </div>

Any suggestions on how I can resolve this issue?

Answer №1

Utilizing an object as a dictionary to translate "slug" into "color" is a helpful approach.

The color attribute can be defined within the categories.map inner function for ease of implementation.

I made sure to remove the id="cat" attribute to prevent any issues with duplicated IDs, which can cause complications.

const colorMap = {
  "animation": animColor,
  "decor": decorColor,
  "illustrations": illuColor,
  "developpement-visuel": devVisuel,
  "realisations": real,
  "croquis": croquis
};

   <div>
            <Header
                categories={categories}
                homepage={homepage} />
            <div className="hidden md:block px-5 pt-10">
                <a className="hover:no-underline " href="/">
                    <h3 className="text-xl uppercase tracking-widest mb-4">{homepage.attributes.hero.title}</h3>
                </a>
                <h5 className="text-sm mb-10">{homepage.attributes.bio.text}</h5>
                <nav>
                    <ul>
                        {categories.map((category) => {
                            return (
                                <li key={category.id} className="mb-4">
                                    <Link href={`/category/${category.attributes.slug}`}>
                                        <a className="uppercase font-light text-sm" style={{color: ${colorMap[category.attributes.slug]}}>{category.attributes.name}</a>
                                    </Link>
                                </li>
                            )
                        })}
                    </ul>
                </nav>
            </div>
        </div>

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

The CSS navigation bar is not properly aligned in the center

This menu was constructed by me: JSBIN EDIT ; JSBIN DEMO Upon closer inspection, it appears that the menu is not centered in the middle of the bar; rather, it is centered higher up. My goal is to have it positioned lower, right in the middle. I ...

Using javascript to locate and substitute a word divided among multiple tags - a step-by-step guide

I need to utilize JavaScript to locate and substitute a word that has been separated into multiple tags. For instance, consider the following HTML code: <html> <body> <div id="page-container"> This is an apple. ...

I'm having trouble establishing a connection between Firebase Realtime Database and Vue.js

I am having trouble establishing a connection to the Firebase Realtime Database. import { initializeApp } from "firebase/app"; // Remember to add any necessary SDKs for Firebase products // For more information, visit: https://firebase.google.com ...

What is the functionality of click-cell.bs.table?

Is it possible to expand the row below a table by clicking on a cell in the row above with the use of click-cell.bs.table instead of click-row.bs.table? I am currently achieving this functionality using click-row.bs.table and bootstrap table. How can I m ...

The JSONLoader object successfully links to a URL but encounters issues with relative paths

Currently facing a minor but persistent issue with THREE.js and seeking assistance. Upon observation, I've discovered that linking a three.js 3D object using an URL functions properly. However, when a relative path is used, only a black window appear ...

Is ASP.NET MVC the better choice over XMLHttpRequest?

I am utilizing angular-file-upload to upload a file in my AngularJS app. There are two uploads: upload OK Content-Length: 3515744 Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryBw0EMfNfB9biF4Kn Content-Disposition: form-data; name= ...

Adjusting the border color when two checkboxes are chosen (and simultaneously deactivating the others)

I'm struggling to understand how to disable the remaining checkboxes after two are selected and change the border color of the "checkbox_group" to red. Can someone help me with this? Here is the JavaScript code I have so far: $(document).ready(funct ...

What could be the reason for one AngularJS component displaying the ng-model value correctly while the other one fails to do so?

I am currently working on creating a set of dynamic components that can be imported into a main component. It is much more convenient to nest components inside one another when I can pass all objects into a single binding instead of creating multiple bindi ...

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 tooltip feature is functioning properly on the button, but unfortunately it is not working

I am incorporating Tooltips into my project, utilizing Vue 3 and Bootstrap 5. In the script section, I have included the following: <script> import { Tooltip } from "bootstrap/dist/js/bootstrap.esm.min.js"; export default { mounte ...

The drop-down list was designed with a main button to activate it, but for some reason it is not functioning properly. Despite numerous attempts, the list simply will not display as intended

<html> <body> <button onclick="toggle()" class="nm" > main</button> <div class="cntnr" style="display : none;"> <ul class="cnkid"> <li class="cnkid"><a class="cnkid" ...

Place the values of an array into separate HTML textboxes

I am looking to display exam results for individuals from a Google spreadsheet. I have managed to find some code and develop an additional HTML page that successfully shows the desired outcome when I click the SHOW link. The app script is as follows: var ...

In AngularJS, the visibility of controller data seems to be elusive to me

Here is a snippet of code from my template: <ul> <li ng-repeat="x in names"> {{ x.name + ', ' + x.country }} </li> </ul> And here is the corresponding JavaScript code: app.controller('TestCtrl', ['$sc ...

Converting Integers to Integers in Javascript: A Step-by-Step

Let's say I have a Method written in JavaScript in GWT(JSNI) which accepts the wrapper data type Integer and I need to convert it into a Primitive Data type inside JS. public static native void nativeMethod(Integer index)/*-{ // What is the best ...

Send a redirect after a certain delay to a URL stored in a variable outside of the current scope

Upon making an ajax request, the JSON response contains a link that needs to redirect the user to another page after 3 seconds. The current approach used is: response = JSON.parse(res); var link = response.link; setTimeout("window.location.href=link",300 ...

Adding a background image in javascript using data from a MySQL database

My current tech stack includes CodeIgniter, vanilla JavaScript, AJAX, CSS, and MySQL. I am trying to figure out how to set the background of an image that is stored in a MySQL database. While the following code is error-free and working perfectly, my cha ...

javascript utilizing underscorejs to categorize and aggregate information

Here is the data I have: var dates = [ {date: "2000-01-01", total: 120}, {date: "2000-10-10", total: 100}, {date: "2010-02-08", total: 100}, {date: "2010-02-09", total: 300} ]; My goal is to group and sum the totals by year like this. ...

How to validate text from a <span> tag using Selenium WebDriver and JavaScript

Is there a way to retrieve the value from the span tag using this code snippet? var error = driver.findElement(webdriver.By.id('error-container-text')).getAttribute('innerHTML'); When I run the above code, I get a response that looks ...

Sending a photo to a customer and launching it in a fresh browser window or tab with MVC 5

My question may be simple, but I find myself a bit puzzled. In my application, whenever a user clicks on an image's thumbnail, the ID of that thumbnail is sent to a controller action using AJAX: [HttpPost] public ActionResult GetHiResImage(string thu ...

Switch out the DOM element for either the opening tag or the closing tag only

Currently, I utilize Blogger for my blogging needs. However, I have encountered an issue where pressing enter in the Rich Text Editor generates <br /> (line break) tags rather than <p></p> (paragraph tags). Unfortunately, there is no appa ...