Modify background color of a div depending on the text within the div

At this website, I have a unique "status tag" (such as Diesel, Auto, Manual, etc) displayed on each inventory picture. I am looking to dynamically change the background color of the tag based on the text within the DIV element.

Below is the code snippet that I currently have:

<script>
$(function() {
    var text = $('.image-container>.status-tag').text().toLowerCase(), color;
    switch (text) {
     case 'Diesel':
        color = '#ff0000';
        break;
     case 'AUTO':
        color = '#6dc8bf';
        break;
     default:
        color = '#39d52d';
    }
    $('.image-container>.status-tag').css('background', color);
});
</script>

Despite setting the colors, only the default color is appearing on the site. I have tried implementing the code but haven't been successful in achieving the desired result based on the text content.

This code was sourced from a different post (original code here) and adapted for my website, but I seem to be experiencing some issues in making it work correctly. Any assistance in resolving this matter would be greatly appreciated.

Answer №1

$(function() {
    //var text = $('.image-container>.status-tag').text().toLowerCase(), color;
    $('.image-container>.status-tag').each(function(){
    console.log($(this).text());
      var text = $(this).text().toLowerCase();
    switch (text) {
     case 'diesel':
        color = '#ff0000';
        break;
     case 'auto':
        color = '#6dc8bf';
        break;
     default:
        color = '#39d52d';
    }
    $(this).css('background', color);
    });
});
<!DOCTYPE html>
<body>
 <div class="image-container">
   <div class="status-tag" style="height:50px;width:50px;margin-top: 10px; margin-bottom: 10px;">Diesel</div>
   <div class="status-tag" style="height:50px;width:50px;margin-top: 10px; margin-bottom: 10px;">AUTO</div>
   <div class="status-tag" style="height:50px;width:50px;margin-top: 10px; margin-bottom: 10px;">Bleh</div>
  </div>
</body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

A solution has been provided above, in a runnable format. It addresses the issue of comparing text strings with different cases and handling multiple image containers with individual switch cases. Additionally, an example of applying styles after an ajax call is demonstrated using jQuery.ajax().

By iterating through each .image-container>.status-tag element, the switch cases can be correctly applied to change the background color. The .done() function is recommended for handling tasks after an ajax call to ensure proper execution.

Answer №2

In response to the comment, I am providing an answer for better clarity. When defining the variable text, you are converting all text to lowercase, which is a good practice in most cases. This allows for flexibility in using a mix of upper and lowercase letters in your markup while still functioning correctly. However, it is essential to ensure that the case matches exactly in the switch statement for it to work accurately.

$(function() {
    var text = $('.image-container>.status-tag').text().toLowerCase(), color;
    switch (text) {
     case 'diesel': // modified here
        color = '#ff0000';
        break;
     case 'auto': // also modified here
        color = '#6dc8bf';
        break;
     default:
        color = '#39d52d';
    }
    $('.image-container>.status-tag').css('background', color);
});

Answer №3

Summary:

  1. Shift your script to the bottom of the body tag
  2. Utilize each method for status flags
  3. Convert your switch statements to lowercase as well

Since your script is currently located in the head section, it may run before the body is fully rendered, resulting in an inability to locate your elements. Therefore, relocate it to the end of the body section.

Additionally, as you are using the jQuery element selector, you are receiving an array of elements, not just one. Ensure to iterate over all of them using an each method. Something similar to this (remember to switch to lower case for your switch cases to find a match):

$(function() {
    var textElements = $('.image-container>.status-tag'), color;
    
    textElements.each(function(index, element){
      var text = $(element).text().toLowerCase();

    switch (text) {
         case 'diesel':
            color = '#ff0000';
            break;
         case 'auto':
            color = '#6dc8bf';
            break;
         default:
            color = '#39d52d';
        }
      $(element).css('background', color);
    })
    
    
});

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

Embracing this web design framework with Rails

Hey there, I am currently trying to integrate a free CSS/HTML/JavaScript template into my Rails project. You can download the template from here. The template consists of an index page, a single CSS file, and two JavaScript files. To implement this templa ...

Issue with bidirectional binding on angular material slide toggle not functioning as anticipated (Angular 4)

My angular material slide-toggle implementation seems to be working, but I'm facing an issue where it doesn't bind the value to the relevant variable as expected. // other irrelevant imports above.. import {MatDialog, MatDialogRef, MAT_DIALOG_DA ...

How can I troubleshoot a C# web method called from an AJAX request in

I have a asp.net (web forms) c# code behind page that contains a web method which I trigger through an ajax call on the same page. Upon making the ajax POST call, I encounter a generic "Internal server error has occurred" message. To troubleshoot this is ...

What is the method for determining the size of a WeakMap?

I am working with a WeakMap that looks like the following: let newObj = new WeakMap(); let key1={"a":1}; let key2={"b":2}; let key3={"c":3}; newObj.set(key1,"value1"); newObj.set(key2,"value2"); newObj.set( ...

I'm struggling to grasp how to effectively utilize a JSON Object in this situation

In my coding project, I am looking to utilize Javascript in order to create a JSON or array that will house pairs of data for 'id' and 'ip'. This way, if I need to retrieve the 'ip' for a specific 'id=123', I can eas ...

What is the best method for embedding JSON data into a script tag within a Zope Chameleon template?

Creating a pyramid/python application where the view callable passes in an array variable called data, structured as [[[x1,y1,z1,],...],[[v1,v2,v3],...]] In the view callable: import json jsdata = json.dumps(data) I aim to place this data within a java ...

Utilizing AngularJS to create a dynamic autocomplete feature with data sourced

I'm currently implementing an autocomplete feature using the REST Countries web service. The goal is to provide suggestions as the user starts typing in an input field, and once a country is selected, display information about it. I am considering usi ...

Top method for integrating configuration into a module

I'm trying to create a module called something.js that depends on a configuration, but I don't want the module itself to explicitly require the config. Additionally, I need my code editor to be able to analyze the module and provide autocomplete ...

In JavaScript, JSON data is parsed using a comma separator

Here is the format of my data: [{"QualID":1,"Qualification":"Van Driver"},{"QualID":3,"Qualification":"Safety Cert"},{"QualID":4,"Qualification":"Welder"}] I am look ...

Issue encountered: Next.js has failed to hydrate properly due to a discrepancy between the initial UI and server-rendered content

Uncertain about the cause of this error? The error seems to disappear when I remove the provided code segment. What is triggering this error in the code snippet and how can it be fixed? <div className="relative flex flex-col items-center pt-[85.2 ...

Unable to properly delete data in Express/Postgres

After developing a Kanban board using JavaScript without any frameworks on the front end, I integrated Express/Postgres on the back end. However, I am encountering an issue with the 'Delete' operation. While all other CRUD operations are functio ...

Exception encountered with HTML5 cache manifest

I attempted to implement the application cache feature on my website, but I am facing a major issue. I only want to cache three specific files: style.css, favicon.ico, and script.js. The problem arises when the browser also caches other files such as inde ...

The issue arises when I try to retrieve information from MySQL using Ajax, as it appears

I am currently working on developing an ecommerce website. In order to display products, I am fetching data from a database. My goal is to allow users to add products to their cart without having to refresh the page. I have attempted to use AJAX for this ...

Employing selenium.isElementPresent in Selenium 1 does not have the capability to identify an element that is dynamically added to the Document Object Model (

After trying out various locators, I have yet to find one that can detect an element that was added to the DOM. Below is my latest attempt at solving this issue: selenium.fireEvent("//button[2]", "click"); waitUntil(new Condition() { @Override pu ...

Adding a Close Button to a MaterializeCSS Card or Card-Panel

Hey everyone! I'm looking for guidance on how to add a close button (x) to a card or card-panel in MaterializeCSS. While Bootstrap offers an Alert component, unfortunately MaterializeCSS does not have one readily available. Does anyone know of a wor ...

Dealing with null route parameters for Express applications

I am facing a challenge in handling an empty route parameter when a path is not specified. My intention is to return a new date if the route parameter is empty. However, the server's response so far is: Cannot GET /api/timestamp/ app.get("/api/timest ...

The box-shadow feature seems to be disabled or ineffective when trying to send HTML content via

I am having a unique approach to sending emails using html. To combat the issue of image blocking by email providers, I have resorted to utilizing box-shadow to create the images I require. The strange thing is that it appears perfectly fine in the browser ...

What is the process of displaying JSON headers using JavaScript?

Although it may seem like a simple question, I am new to JSON. Can someone explain how to display a heading in the console? This is the code I have: var jsonstr = '{"profile":{"name" : "raj","age":"35&qu ...

Using JavaScript, swap out the default "item added to cart" message with a custom Sweet Alert notification in WooCommerce

After removing the standard "Added to cart" message provided by WooCommerce, I have implemented a new code snippet using Sweet Alert. The goal is to eliminate all default "added to cart" messages and exclusively use the Sweet Alert feature. Although my co ...

auto-scrolling webpage as elements come into view

Here is some jQuery code I have: $(".col-md-12").hide(); $(".button-div").hide(); $(".featurette-divider").hide(); $(".footer").hide(); $(".first").fadeIn(1000); $(".second").delay(900).fadeIn(1000); $(".third").delay(1800).fadeIn(1000); $(".fourth").dela ...