Is there a way to make negative numbers in a JSON response from JS turn red easily?

I am currently working on a website ticker tape and have successfully gathered all the necessary data. However, I am facing an issue with changing the color of the daily price change based on whether it is positive or negative. I'm unsure where to begin troubleshooting this. Any guidance would be highly 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"];
    
    // Add logic here to change text color based on positive/negative values
    
  }
};
xhttp.open("GET", "https://cloud.iexapis.com/v1/stock/market/batch?&types=quote&symbols=aapl,amzn&token=pk_6925213461cb489b8c04a632e18c25dd", true);
xhttp.send();
}

Answer №1

To determine the color, simply evaluate the value and assign accordingly. It is assumed that the values extracted from the JSON are numeric; if not, you can utilize parseFloat() for conversion:

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

An alternative approach involves applying the same logic to assign a className and defining corresponding colors in CSS.

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

Explore our interactive map and widget features that will seamlessly fill your browser window for a

Struggling to make a webpage with a Google Map, Chart, and Grid expand to fill the available space on the screen. Tried various CSS tricks but nothing seems to work. Check out this simplified example in JsFiddle that showcases the issue: http://jsfiddle. ...

Which slider was featured in the unity3d.com/5 website?

While browsing the internet, I came across the website and was intrigued by the slider effect featured in the "graphics" section. I am eager to figure out how to replicate that stunning visual effect. ...

Unable to click, but can only be activated by touchstart or mousedown

Is it possible to bind a 'click' event to a paragraph? Here is the function I am using: $(document).on('touchstart mousedown',"p span.text", function(e) { console.log('I was clicked'); *more code here* }); When I ...

What is the significance of placing items in a list box? Can you explain the statement "opt as opt for opt in months" in the context of AngularJS?

Visit this link for an AngularJS listbox example Displayed below is the code snippet: <select style="width: 100%;" size="7" ng-model="currentItems" multiple ng-multiple="true" ng-options="opt as opt for opt in months"> </se ...

Guide to successfully redirecting to a new page post login, along with sending a token as a handler to middleware using the express framework

My application utilizes nextJS, express JS, and JWT. I have created two pages - a login page and an admin page where the latter is protected and only accessible after verifying the token using JWT. My goal is to redirect users to the admin page immediately ...

What could be causing my callback function to fail when used within a nested function?

I am currently utilizing the callback function in conjunction with Socket.io as shown below: loadData(callback) { var client = new SyncClient(this.socket, this.project); this.client = client; //From my data function client.on("connected", () => { ...

Using Jquery to detect changes in a Datalist element in an HTML5 document

This snippet illustrates the code: <input name="cmbname" type="text" id="cmbname" list="listcmbname" autocomplete="off" runat="server"> <datalist id="listcmbname"> <option data-id="1" value="a"></option> <optio ...

Issue with form not capturing information from dynamically generated fields

I'm working on creating a dynamic form for user input of on/off instructions in pairings. The HTML code defaults with one pair, and the user can add additional pairs using a button. However, upon form submission, Angular is only reading the values fro ...

Expand the video comparison slider to occupy the entire width and height

I am striving to develop a video comparison slider that fills the height and width of the viewport, inspired by the techniques discussed in this informative article: Article Despite my efforts, I have not been successful in achieving this effect so far a ...

Error: The function (0, _context_stateContext__WEBPACK_IMPORTED_MODULE_4__.useStateContext) is not of type TypeError

I have been working on setting up a useContext() for an online store to share data across all components and manage product quantities. However, I've hit a snag while trying to import the context(). Everything was running smoothly until I added this p ...

Revamp the Design Layout of a Drag-and-Drop Tool

After experimenting with a drag and drop feature using jQuery, I discovered the following useful code snippet. Here's how it functions: $( "#sortable1, #sortable2" ).sortable({ connectWith: ".connectedSortable" }).disableSelection(); #so ...

Using Vue to iterate through elements

I am struggling to loop through an array in a Vue component without duplicating the element specified in the 'v-for' directive. I have consulted the official Vue.js API documentation, as well as various online articles, but haven't found a s ...

What is a way to determine if there are any active AJAX requests on a page using jQuery?

Is there a method to detect if an AJAX request is currently active on the page during the $(window).load event? I am looking to trigger an event once all AJAX requests have finished. I attempted using: .ajaxStop(function(){ }) However, I would like to ...

Experiencing difficulties in arranging Bootstrap columns based on media queries

I am creating a layout for a website that requires 4 columns. When the screen is in desktop mode or wider than tablet width, it should show all 4 columns with the outer 2 being used for padding only. However, in mobile mode, the outer 2 columns should di ...

What is the best way to use regex for splitting an array?

I have a string that I need to convert into an array of objects const str = "Nike (brand|category) shoes(product) for women(o)" Expected result let output = [ { key:"Nike", value:["brand","category"] }, { key:"shoes", value:["product"] }, { ...

How can multiple elements be connected to an onclick action?

I'm having trouble figuring out how to use an onClick action with jQuery for all the elements in a list of attached files. Here is a snippet of my HTML file: <p>Attachments</p> <div> <ul id="attach"> <li id="KjG34 ...

Is it necessary to clean and reinstall node_modules every time I deploy in a production environment?

We manage over 10 production servers and each time we update our dependencies, performing a clean installation seems more controlled but also slower. The issue is that the devops team is concerned about the time it takes to perform a clean npm install aft ...

Update the Ngrx reducer when the component is present on the page

One dilemma I am facing involves managing two components within a page - an update user form and a history of events. Each component has its own reducer (user and events). My goal is to update the list of events in the store through an API call once the us ...

Is there a problem with `window.google` being undefined in a React

Every time I call window and use console log, a google prop appears as shown below: https://i.sstatic.net/dSMs8.png But then when I attempt to call window.google, it returns undefined. Am I overlooking something here? ...

AngularJS dropdown not reflecting changes when using ng-selected

While working with AngularJS, I have encountered an issue where the first child of the select element remains empty despite my efforts to populate it. Below is the HTML code snippet: <select id="connectTV" aria-label="How many Dish TVs" ng-model="conn ...