Adjust the color of a DIV based on the text value retrieved from an external source

I am looking to dynamically change the text color between red and green based on a numeric value received from an external source (API).

If the value is greater than or equal to 50, it should be displayed in red. If it's less than 50, then it should be displayed in green.

Any suggestions on how to achieve this?

Chris

const api = "https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/query?where=county%20%3D%20%27SK%20stuttgart%27&outFields=cases,deaths,county,last_update,cases7_per_100k,recovered&returnGeometry=false&outSR=4326&f=json";

fetch(api).then((response) => {
    return response.json();
}).then((json) => {
    const cases = json.features[0].attributes.cases;
    const deaths = json.features[0].attributes.deaths;
    const cases7Per100k = json.features[0].attributes.cases7_per_100k;
    const recovered = json.features[0].attributes.recovered;
    const lastUpdate = json.features[0].attributes.last_update;
    console.log(cases7Per100k)
    document.getElementById("cases7Per100k").innerHTML = Math.round(cases7Per100k * 10) / 10 || 0;
});
<p id="cases7Per100k"></p>

Answer №1

If you want to change the color, you can use element.style.color. (Link)

This example demonstrates how to do it:

const api = "https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/query?where=county%20%3D%20%27SK%20stuttgart%27&outFields=cases,deaths,county,last_update,cases7_per_100k,recovered&returnGeometry=false&outSR=4326&f=json";

fetch(api).then((response) => {
  return response.json();
}).then((json) => {
  const { cases, deaths, cases7_per_100k, recovered, last_update } = json.features[0].attributes;
  console.log(cases7_per_100k)
  
  const p = document.getElementById("cases7Per100k");
  p.innerHTML = cases7_per_100k.toFixed(1) || 0;
  p.style.color = cases7_per_100k > 50 ? '#ff0000' : '#00ff00';
});
<p id="cases7Per100k"></p>

Answer №2

perhaps experimenting with the returned value and applying a style?

const api = "https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/query?where=county%20%3D%20%27SK%20stuttgart%27&outFields=cases,deaths,county,last_update,cases7_per_100k,recovered&returnGeometry=false&outSR=4326&f=json";

fetch(api).then((response) => {
  return response.json();
}).then((json) => {
  const cases = json.features[0].attributes.cases;
  const deaths = json.features[0].attributes.deaths;
  const cases7Per100k = json.features[0].attributes.cases7_per_100k;
  const recovered = json.features[0].attributes.recovered;
  const lastUpdate = json.features[0].attributes.last_update;
  console.log(cases7Per100k)
  let test = Math.round(cases7Per100k * 10) / 10 || 0;
  if ( test >= 50 ) {  document.getElementById("cases7Per100k").style.color='green';}
  else {  document.getElementById("cases7Per100k").style.color="red";}
  document.getElementById("cases7Per100k").innerHTML = test;
});
<p id="cases7Per100k"></p>

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

I keep receiving a 400 (Bad Request) error when trying to delete with my REST API

I've successfully created an API and have managed to make POST and GET requests work flawlessly. However, I'm facing some trouble with the DELETE request. Every time I try to execute it, I encounter a 'DELETE http://localhost:3000/api 400 (B ...

Prevent the need to go through the keycloak callback process each time the page is

I have integrated keycloak as an identity provider into my React application. I successfully added the keycloak react dependency via npm. Below are the versions of the keycloak react npm modules on which my application depends : "@react-keycloak/web ...

Searching for a specific data point within the latest entry of a JSON file using Javascript

I am currently in the process of utilizing a sensor to measure temperature, which is then stored in a mongo database. This data can be accessed as a JSON file by visiting ('/data'). My goal is to determine the latest entry and extract the temper ...

What is the best way to access and interpret a JSON file within an Angular application?

I am facing difficulties while trying to load a JSON file from my local disk in order to populate a FabricJS canvas with the data. Currently, I am encountering issues retrieving the data from the file. Here is what I have attempted so far. app.html < ...

Nested routing in Nextjs is encountering issues when implemented with a specific file

I'm struggling with setting up routes in Next.js. When I create the path "/app/[locale]/admin/page.tsx," I can access http://url/admin/ without any issues. However, when I try to set up "/app/[locale]/admin/login.tsx," I encounter an error and cannot ...

Is the next function triggered only after the iframe has finished loading?

First and foremost, I understand the importance of running things asynchronously whenever possible. In my code, there exists a function known as wrap: This function essentially loads the current page within an iframe. This is necessary to ensure that Jav ...

Styling the background of a container in CSS using Bootstrap

Currently, I am utilizing bootstrap and trying to find an elegant solution for adding a background to my container. Specifically, I am working with the bootstrap class container, as opposed to container-fluid. The official Bootstrap documentation advises ...

iOS 11's Mobile Safari presents a challenge for web apps with the nav bar overlapping the top portion of the screen, cutting off content that relies on

When using 100vh on Mobile Safari, it fails to account for the height of the lower navigation bar. For example, look at the screenshot below. To show my app-like footer, I have to manually subtract 74px from the container's height in a somewhat messy ...

Building Your Initial HTTP Server using Node.js

Hey everyone, I'm relatively new to node.js but have made some progress. Following the steps in this tutorial, I was able to create my first "example" server. However, there are a few things that I don't quite understand. Could someone please exp ...

Creating a React Native project without the use of TypeScript

Recently I dived into the world of React Native and decided to start a project using React Native CLI. However, I was surprised to find out that it uses TypeScript by default. Is there a way for me to create a project using React Native CLI without TypeS ...

Changing the color of a pseudo element in Material-UI

I'm having trouble changing the border color of the ::after pseudo element on a standard text field from MUI. I've been unable to figure it out. <TextField id="standard-basic" label="Email" variant="standard"/> ...

Retrieving outcome of Solidity contract function using web3-1.0.0-beta.27

I am using web3 1.0.0-beta.27 and the pragma solidity is set to ^0.4.2. contract Charity{ function ping() public constant returns (uint) { return 200; } } Currently, I am compiling and calling it in typescript with: import * as fs ...

The matMul function encountered an error due to a mismatch in the inner shapes of the Tensors. The shapes provided were 684,1 and 2,1, and the transposeA and transposeB parameters were both set

I am completely new to the world of AI and tensorflow.js. Currently, I am following a Machine Learning course by Stephen Grider. I was expecting an output after running the code below, but instead, I encountered an error. Can someone please assist me? Her ...

How can I override the maximum body width to enable specific div elements to extend beyond that limit?

While I've come across similar questions to mine, none of them seem to solve my specific issue. Essentially, I've set the body width to 960px, which is a common standard practice. However, there are certain elements such as header, footer, and so ...

Is it possible to dynamically adjust the container size based on its content with the help of *ngIf and additional directives?

I have a single-image container that I need to resize when editing the content. The size should adjust based on the incoming content. See the images of the containers below: Image 1: This is the container before clicking on the edit button. https://i.sst ...

HTML/CSS code for a header with elements centered across the full width of the screen

Having an outdated WordPress theme from 2010, I wanted to give it a modern touch by adding a sticky header. I found a plugin called myStickymenu that seemed to work well. However, my current theme's header has a fixed width of 960px and I desired to m ...

Issues with PHP Form Email DeliveryIt seems that there is a

I currently have a ready-made form that is constructed using html, css, jquery, and ajax. It's basically copied and pasted onto my contact page for now. This is the code I include before the html tag on the contact.php page. <?php session_name(" ...

Arrange a div within a list element to create a grid-like structure

My current structure is as follows: <ul class="wrap-accordionblk"> <li class="accordionblk-item"> <div class="accordionblk-header"> <div class="row-fluid"> <div class="infoblk"> <label>SESSION ID ...

Communication between the Node development server and the Spring Boot application was hindered by a Cross-Origin Request

Here is the breakdown of my current setup: Backend: Utilizing Spring Boot (Java) with an endpoint at :8088 Frontend: Running Vue on a Node development server exposed at :8080 On the frontend, I have reconfigured axios in a file named http-common.js to s ...

Utilizing ReactJS to retrieve configuration settings from a YAML file, similar to how it is done

Our team is currently using a full-stack multi-microservice application where the backend java components utilize the spring @value annotation to fetch configuration values from a yml file. This method has been effective and even the Java side of our UI c ...