0

I am receiving and displaying a numeric value from a external source (API). Now I need the color of the text change between RED and GREEN, depending on the value.

≥50 = red & <50 = green

Do you guys have any idea?

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>
ChrisG
  • 19
  • 2

2 Answers2

1

You can set the color through element.style.color. (Link)

The following should work:

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>
freakimkaefig
  • 409
  • 5
  • 19
0

maybe testing the value return and apply 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>
G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129