Is there a way to change the color of a number's font based on whether it is preceded by a "+" or "-" sign?

I am currently working on a stocks widget and I have a specific requirement. Whenever there is a change in value in the Change or Changeinpercent columns, I need to dynamically set the font color to red for a decrease (-) or green for an increase (+).

Here is the progress I've made so far: http://jsfiddle.net/thetuneupguy/r2Bca/

$(function() {
    $.getJSON('http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20yahoo.finance.quotes%20WHERE%20symbol%20in(%22GCF14.CMX%22%2C%22SIF14.CMX%22%2C%22PAH14.NYM%22%2C%22PLF14.NYM%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=', function(data) {
    console.log("data: ", data);
    console.log(data.query.results.quote);
    $.each(data.query.results.quote, function(key, obj){
        var $tr = $('<tr/>', {'class': 'my-new-list'}).appendTo('#blk-1 table');            
        $tr.append($('<td/>').text(obj.Name || "--"));
        $tr.append($('<td/>').text(obj.Ask || "--"));
        $tr.append($('<td/>').text(obj.Bid || "--"));
        $tr.append($('<td/>').text(obj.Change || "--"));
        $tr.append($('<td/>').text(obj.ChangeinPercent || "--"));
        });

    });
});

Answer №1

Start by incorporating these two CSS directives:

.increase{
    color:green;    
}
.decrease{
    color:red;
}

Next, instead of the following code snippet:

$tr.append($('<td/>').text(obj.ChangeinPercent || "--"));

Modify it to:

var $td = $('<td/>').text(obj.ChangeinPercent || "--");    
if(/^\+/.test(obj.ChangeinPercent || '')) $td.addClass("increase");  //Apply green if starting with '+'    
if(/^-/.test(obj.ChangeinPercent || '')) $td.addClass("decrease");  //Apply red if starting with '-'
$tr.append($td);

Explore the demonstration here: http://jsfiddle.net/edgarinvillegas/r2Bca/3/

Answer №2

// To ensure that values always have a + or -
(obj.Change.substr(0,1) == '+') ? changeClass = 'green' : changeClass = 'red';
(obj.Change.substr(0,1) == '+') ? changeInPercentClass = 'green' : changeInPercentClass = 'red';

$tr.append($('<td class="'+changeClass+'">').text(obj.Change || "--"));
$tr.append($('<td class="'+changeInPercentClass+'">').text(obj.ChangeinPercent || "--"));

I made an update to the Fiddle file.

http://jsfiddle.net/r2Bca/4/

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

Issue with character encoding in jQuery-ui tabs

Special characters in Swedish are replaced when configuring the tabTemplate option. For instance, using "ö" in the href attribute: var $tabs = $("#tabs").tabs('option', 'tabTemplate', '<li><a href="#ö">#{label}</ ...

- Challenges with internal systems

I have a dialog window where I want to display a confirm dialog when clicking Cancel. To achieve this, I am creating a div element with some text that should be shown in the confirm dialog. However, the issue I'm facing is that the text intended for t ...

Creating a Jax RS response that produces application/json: the best way to enclose a basic string

Here is my REST Service implementation: @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response authenticateUser(CredentialsDTO credentialsDTO) { try { authService.login(credentialsDTO.getUsername(), ...

What is the best way to receive a user's input date in Dynamics 365 using HTML/JavaScript?

My HTML webform is set up to capture user input like address, card number, city, and state in text format. However, within Microsoft Dynamics 365, I have a custom entity with fields for this information. When a user completes the webform and submits it, a ...

Is Angular4 preloaded with bootstrap library?

I started a new angular4 project and wrote the code in app.component.html <div class="container"> <div class="row"> <div class="col-md-1">.col-md-1</div> <div class="col-md-1">.col-md-1</div> <div class ...

Can you set up an automatic redirect after a payment is made on paypal.me?

Is there a way to automatically redirect users to a "successful payment" landing page after they make a payment on paypal.me? While PayPal offers an "Auto Return" feature, I am uncertain if it is applicable for paypal.me or if there are alternative methods ...

`Unexpected error occurred during JSON parsing due to a unrecognized selector being sent to the

Can someone assist me in debugging this piece of code? dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(queue, ^{ NSError *error = nil; NSURL *urls = [NSURL URLWithString:[NSString stringWi ...

Is there a function called 'onViewportChange' in media queries that triggers a search in the .css file for applicable styling?

So I'm not entirely sure about all the specifics, but my understanding is that each time a new HTML element is created, it checks through all linked CSS files and inline styles to see if those styles should be applied to that element. This suggests t ...

Having trouble populating and submitting a selected option from a dropdown menu in Angular?

Upon loading the page, the Category dropdown automatically populates with data from the database. However, when I attempt to select a value from the dropdown and click a button to post the data to a specified URL, an error occurs: ERROR Error: Error tryin ...

Retrieve the values of an array using a foreach loop with data retrieved from an

Hey there! Here is the array obtained from an ajax response: [{"qty":1,"name":"7-test-Professional","part_number":"12231","list_price":"800"}, {"qty":1,"name":"Senior Professional Forester","part_number":"","list_price":"97.000000"] I'm attempting t ...

Using a jQuery gallery can cause links to become unresponsive and unclickable

While creating a responsive webpage with the Zurb Foundation framework, I encountered an issue when trying to incorporate nanoGallery which also uses jQuery. After adding the gallery scripts, the top menu generated by the Foundation script became unclickab ...

Customizing Material UI Stepper styles using CSS API

I am trying to customize the text color (represented by an SVG Icon) in Material UI StepIcon for active and completed steps only. Currently, I have successfully changed the icon color for those steps. This is how my custom MuiTheme appears: export default ...

I'm looking for a way to automatically execute the script in my .json file every time I open my index.html page. Can anyone help me

Inside the .json file, I have a script section that requires me to manually run it everytime by typing npm run (the script's name) in the terminal when I want to open my html page on the server. Is there a way for this process to be automated so that ...

Attempting to align a navigation block next to an SVG image

On my website, I envisioned a photoshopped image featuring a SVG picture of a book on the left and a "navigation block" on the right. The navigation block consists of links that redirect to other pages but it's not displaying properly. You can view th ...

Tips for transforming my JSON format into the necessary column layout for C3.js

The data structure returned by my API is as follows. However, I need to reformat this structure for use in C3.js. { "data":{ "test7":[ { "Date":"2016-04-26 00:00:00", "aId":7, "Amount":436464, "Piece":37 ...

Close the overlay by clicking outside of it

I'm working on creating a unique pop-up window that appears when a customer adds a product to their cart. The design features red and green background divs with a darker overlay (#overlay-daddy) and a white child div (#overlay). My issue arises from ...

How can I identify the currently active partial in mvc3 framework?

Is there a way to dynamically determine which partial is currently active in the DOM so that I can apply CSS to it? Also, how can I create an anchor that allows users to copy and paste a URL to a specific partial? EDIT: Assume I have three links, where t ...

Issue with displaying error message on span element during validation

Is there a way you can recommend for displaying the error message within element with id #genderError instead of after it? errorPlacement: function(error, element) { if (element.attr("name") == "myoptions" ) error.appendTo('#genderError'); ...

determine the vertical dimension of the horizontal scrollbar

I ran into an issue where I needed to determine the height of a horizontal scrollbar. This question and answer recommended using the clientHeight property to calculate the difference. Unfortunately, this method no longer works as shown here: https://jsfid ...

Does the Width Toggle Animation fail to function in FireFox when using jQuery?

Has anyone else encountered this issue with the jQuery animate function not working in Firefox but working fine in IE8, Opera, and Chrome? I'm experiencing this problem and wondering if there's a workaround to make it work in Firefox as well. ht ...