Adjusting the color of multiple identical class DIVs depending on the response value

I have a loop that retrieves different items from the API, each with the same class div for better CSS styling. I am trying to change the background color of each div based on its rarity. However, my current code only makes all divs green. When I add additional else-if statements, it still sets every div to green.

            $.each(data.data.daily.entries, function(i, item) {
            //Creating item cards
            $('body > #cards_daily').append('<div class="card"> ' + item.items[0].name + ' <br> ' + item.finalPrice + '<img src="https://fortnite-api.com/images/vbuck.png" height="20px">' + ' <br> ' + '<img id="image" src="' + item.items[0].images.icon + '"></img>' + '</div>');
            //Debug rarity
            console.log(item.items[0].rarity.displayValue)
            //Trying different values, to match right one
            if (item.items[0].rarity.displayValue === "rare") {
                $(".card").css("background-color", "red"); //Gray

            } else if (item.items[0].rarity.displayValue === "Uncommon") {
                $(".card").css("background-color", "#319236"); //Green

            } else if (item.items[0].rarity.displayValue === "Rare") {
                $(".card").css("background-color", "#4c51f7"); //Blue

            } else if (item.items[0].rarity.displayValue === "Epic") {
                $(".card").css("background-color", "#9d4dbb"); //Purple

            } else if (item.items[0].rarity.displayValue === "Legendary") {
                $(".card").css("background-color", "#f3af19"); //Gold

            } else if (item.items[0].rarity.displayValue === "Icon Series") {
                $(".card").css("background-color", "#00FFFF"); //Cyan

            } else {
                $(".card").css("background-color", "rgb(148, 148, 150)");
            }
        });

Answer №1

In case you are inside a for each loop

item.items[0].rarity.displayValue

The rarity display value of the first element in the array is common for all other elements, so you can utilize the following code accordingly.

Please keep in mind that when selecting items with $(".card"), it will choose all card elements from the DOM. Therefore, it's advisable to segregate the CSS while constructing them.

//Daily offers
fetch('https://fortnite-api.com/v2/shop/br')
    .then(res => res.json())
    .then(data => {
        $.each(data.data.daily.entries, function(i, item) {
            if (data.data.daily.entries[i].bundle != null) {
                return;
            }
            var html='';
            if(item.items[0].rarity.displayValue){
              var bgcolorforDiv=fetchbackGround(item.items[0].rarity.displayValue);
              html='<div class="card" style="background-color:'+bgcolorforDiv+'"> <b>' + item.items[0].name + '</b> <br> <span>' + item.finalPrice + '<img id="v_buck" src="https://fortnite-api.com/images/vbuck.png" height="28px"> </span>' + ' <br> ' + '<img id="image" src="' + item.items[0].images.icon + '"></img>' + '</div>';

            }
            else{
              html='<div class="card"> <b>' + item.items[0].name + '</b> <br> <span>' + item.finalPrice + '<img id="v_buck" src="https://fortnite-api.com/images/vbuck.png" height="28px"> </span>' + ' <br> ' + '<img id="image" src="' + item.items[0].images.icon + '"></img>' + '</div>';
            }
            $('body > #cards_daily').append(html);
        });
    });
function fetchbackGround(rarity){
  var background="rgb(148, 148, 150)";
  switch(rarity){
     case "rare":background="red";break;
     case "Uncommon":background="#319236";break;
     case "Rare":background="#4c51f7";break;
     case "Epic":background="#9d4dbb";break;
     case "Legendary":background="#f3af19";break;
     case "Icon Series":background="#00FFFF";break;
  }
  return background;
}
//Featured offers
fetch('https://fortnite-api.com/v2/shop/br')
    .then(res => res.json())
    .then(data => {
        $.each(data.data.featured.entries, function(i, item) {
            if (data.data.featured.entries[i].bundle != null) {
                return;
            }
            $('body > #cards_featured').append('<div class="card"> ' + item.items[0].name + ' <br> <span>' + item.finalPrice + '<img id="v_buck" src="https://fortnite-api.com/images/vbuck.png" height="28px"> </span>' + '  <br> ' + '<img id="image" src="' + item.items[0].images.icon + '"></img>' + '</div>');
        });
    });

fetch('https://fortnite-api.com/v2/shop/br')
    .then(res => res.json())
    .then(data => {
        $.each(data.data.specialFeatured.entries, function(i, item) {
            if (data.data.specialFeatured.entries[i].bundle != null) {
                return;
            }
            $('body > #cards_featured_special').append('<div class="card"> ' + item.items[0].name + ' <br> <span>' + item.finalPrice + '<img id="v_buck" src="https://fortnite-api.com/images/vbuck.png" height="28px"> </span>' + '  <br> ' + '<img id="image" src="' + item.items[0].images.icon + '"></img>' + '</div>');
        });
    });

//Timer
(function() {
    var start = new Date;
    start.setHours(2, 0, 0); // 02.00

    function pad(num) {
        return ("0" + parseInt(num)).substr(-2);
    }

    function tick() {
        var now...

<footer a {
        text-decoration: none;
        color: white;
    }
}
<!DOCTYPE html>
<html>

<head>

    <title>Fortnite itemshop tracker!</title>
<style type="text/css">

</style>
    <link rel="stylesheet" href="style.css?v=1.0">
    <link rel="apple-touch-icon" sizes="180x180" href="favicon/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="favicon/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="favicon/favicon-16x16.png">
    <link rel="manifest" href="img/site.webmanifest">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

</head>

<body>


    <header>
        <h1>Pinja's daily itemshop tracker</h1>
        <h3>[Work in progress]</h3>
    </header>
    <div id="cards_daily">

        <H1 id="OTSIKKO">Daily offers</H1>
        <div class="timer">
            Daily shop reset in: <span id="time"></span>
        </div>


    </div>
    <div id="cards_featured_special">
        <H1 id="OTSIKKO">Featured specials</H1>
        <div class="timer">
            Bundles are not included!
        </div>

    </div>
    <div id="cards_featured">
        <H1 id="OTSIKKO">Featured</H1>
        <div class="timer">
            Bundles are not included!
        </div>

    </div>
</body>

</html>

Answer №2

From my observations, it appears that the styling of the entire list is based solely on the displayValue attribute of the initial element. Your current code only targets item.items[0], which represents the first item in the list. To customize each card's displayValue, you will likely need to iterate through all items in the list.

Additionally, the code you have implemented uses jQuery to select all elements with the .card class and applies the same background to all of them. To target a specific card for individual background updates, you should pinpoint the exact card you wish to modify instead.

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

Retrieve data from an array of objects nested within another object

Imagine a scenario where there is an object containing an array of objects. let events = { "id": 241, "name": "Rock Party", "type": "party", "days": [ { "i ...

Bring in a function by its name from the ts-nameof package that is not declared in the d.ts export

Recently, I came across a captivating package that caught my interest and I would love to incorporate it into my TypeScript application: https://github.com/dsherret/ts-nameof However, upon attempting to import the nameof function, I realized it was not be ...

An issue occurred while attempting to hover over the text in the SVG map

I have a United States map. This code contains CSS for styling the map with different colors for each state. It also includes an SVG image of the map and text labels for each state name. However, there is an issue with the hover effect on the state name ...

Filter JSON data deeply for specific values

I am attempting to filter JSON data based on user checkbox selections in JavaScript. The challenge I'm facing is implementing multi-level filtering. The data has two dimensions that need to be filtered: first by OS selection and then by a selected que ...

Yii2 does not grant access to session data through AJAX

I'm facing an issue while trying to access yii2 session using nodejs. Below is the code snippet I am working with: Node JS : client.on("request_notification_count",function(e){ //get latest feed id console.log(e); request.get(e.url+"?_ ...

Creating a sophisticated form design with multiple input fields using DIV elements in HTML

I am looking to create a multi-column form layout that allows each row to have a different number of fields. My initial approach was using tables and the colspan attribute within td tags for layout structure. However, I have learned that using tables for l ...

Different Ways to Customize Button Click Events in Angular 9 Based on Specific Situations

In my Angular 9 web application development, I frequently need to integrate Bootstrap Modals like the example below: <div class="modal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="do ...

Ways to invoke a class method by clicking on it

My initialization function is defined as follows: init: function() { $("#editRow").click(function() { <code> } $(".removeRow").click(function() { <code> } } I am trying to find a way to call the class method removeRow directly in the onc ...

Enhancing the styling of checkboxes using CSS and Javascript

My Javascript skills have been put to the test with a simple code snippet that customizes checkboxes by hiding them and using background images in CSS to display checks and unchecks. It's a neat trick, but I'm wondering if it's HTML/CSS comp ...

Uploading image data through jQuery Ajax will not be stored in ModelForm

Recently, I've been experimenting with editing an ImageField using jQuery ajax. To accomplish this task, I decided to utilize the jQuery Form Plugin. Below is the code snippet that demonstrates how I set it up: <form id='form_upload' act ...

Instructions for loading custom field data from a WordPress post using ajax

Even though I am not proficient in PHP programming and unfamiliar with data fetching, I am attempting to create a template that dynamically loads custom field values of posts via AJAX in WordPress. The rationale behind using AJAX for loading these values ...

Is there a way to stop all HTML5 videos except for the one that I want to watch?

On my webpage, I have three HTML5 videos all on one page. My goal is to be able to pause or mute all the videos at once, except for the one that I specifically choose. Initially, I tried using an event listener on the parent div which worked well when clic ...

Enable checkboxes to be pre-selected upon page loading automatically

Although I've found a lot of code snippets for a "select all" option, what I really need is more direct. I want the WpForms checkboxes to be pre-checked by default when the page loads, instead of requiring users to press a button. My goal is to have a ...

What is the significance of incorporating 'Actions' as data within the Redux framework?

According to Redux documentation, creating actions and action creators is necessary. Here's an example: function addTodo(filter) { return { type: SET_VISIBILITY_FILTER, filter } } Next step is to write reducers, like this: function t ...

Problem with Chrome Compatibility for Bootstrap Carousel

My webpage features a carousel implemented as a slider. It seems to be working fine in Firefox and mobile browsers, except for Chrome where it doesn't show up at all. I can't seem to figure out what's causing the issue. Here is the syntax I& ...

Generating random numbers within specified character limits using Javascript and Selenium

Just starting to learn javascript - I am working on creating random user IDs for my selenium test scenarios. The line of code I am using for the value is as follows: javascript{Math.floor(Math.random()*11111)} However, there is a specific field that need ...

Guide to connecting a different HTML page to a thumbnail image using jQuery

let newColumnBlock = $('<div class="col-md-2">'); let newImagePoster = $('<img>'); let newSelectButton = $('<a href="secondPage.html"><button class="selectButton"></button></a>'); let movie ...

I'm currently utilizing the react mui package, specifically @mui/x-date-pickers. Could someone kindly provide guidance on how to customize the color of the

I am currently working with MUI in React and using the DatePicker component from the @mui/x-date-pickers library. The version I am using is 6.0.3. I have encountered an issue where, upon selecting the first day, the specified color changes as shown in the ...

Utilize the camera feature within a designated div element

I'm having trouble understanding why the camera isn't showing up in the div. Am I making a mistake somewhere? <!DOCTYPE html> <html> <head> <script type="text/javascript" src="swfobject.js"></script> </head> & ...

Obtain the maximum or minimum value from an associative array using a function and provided parameters

Here is the code I have so far: <!DOCTYPE html> <html> <body> <button onclick="scanarray('a', 'max')">Test with a, max</button> <button onclick="scanarray('b', 'min')">Test with ...