ethor11
ethor11

Reputation: 47

How to turn negative numbers red from JS JSON response Red?

I am creating a ticker tape for a website and have been able to get all the data I need, however, I can not seem to get the negative change value on the daily price to turn green for up or red for down. I'm not entirely sure where to start. Any help would be greatly appreciated

HTML:

<div id="tickerwrap">
  <marquee>
    <div style="display: inline-block; font-size: 150%">| Apple inc.</div>
    <div style="display: inline-block; font-size: 150%" id=AAPLp></div>
    <div style="display: inline-block; font-size: 150%" id=AAPLchg%></div>
    <div style="display: inline-block; font-size: 150%">| Amazon inc.</div>
  </marquee>
</div>
<script>
document.onreadystatechange = function() {
  if (document.readyState === 'complete') {
    tickertape();
  }
};

JS:

  function tickertape() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var tickertape = JSON.parse(this.responseText);
    document.getElementById("AAPLp").innerHTML = tickertape["AAPL"]["quote"]["latestPrice"];
    document.getElementById("AAPLchg%").innerHTML = tickertape["AAPL"]["quote"]["changePercent"];
    document.getElementById("AAPLchg").innerHTML = tickertape["AAPL"]["quote"]["change"];
    document.getElementById("AMZNp").innerHTML = tickertape["AMZN"]["quote"]["latestPrice"];
    document.getElementById("AMZNchg%").innerHTML = tickertape["AMZN"]["quote"]["changePercent"];
    document.getElementById("AMZNchg").innerHTML = tickertape["AMZN"]["quote"]["change"];
  }
};
xhttp.open("GET", "https://cloud.iexapis.com/v1/stock/market/batch?&types=quote&symbols=aapl,amzn&token=pk_6925213461cb489b8c04a632e18c25dd", true);
xhttp.send();

};

Upvotes: 0

Views: 395

Answers (1)

slebetman
slebetman

Reputation: 113906

Just check the value and set the color. I'm assuming the values form the JSON are numbers, if not you can use parseFloat() to convert them to numbers:

if (tickertape.AAPL.quote.change < 0) {
    document.getElementById("AAPLchg").style.color = 'red'; // or #f00
}
else {
    document.getElementById("AAPLchg").style.color = 'green'; // or #0f0
}

Alternatively you can use the same logic to add a className and define the colors in CSS.

Upvotes: 1

Related Questions