Reputation:
I'm creating a stocks widget. If a value in the Change or Changeinpercent columns changes, I want to be able to set the font color to red for (-) a decrease or green for (+) and increase in value.
Here is what I've got 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 || "--"));
});
});
});
Upvotes: 0
Views: 71
Reputation: 646
// Assuming the values will have always 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 updated the Fiddle
Upvotes: 0
Reputation: 18344
First, add these 2 css rules:
.increase{
color:green;
}
.decrease{
color:red;
}
Then, Instead of:
$tr.append($('<td/>').text(obj.ChangeinPercent || "--"));
You should do:
var $td = $('<td/>').text(obj.ChangeinPercent || "--");
if(/^\+/.test(obj.ChangeinPercent || '')) $td.addClass("increase"); //If it starts with '+', make it green
if(/^-/.test(obj.ChangeinPercent || '')) $td.addClass("decrease"); //If it starts with '-', make it red
$tr.append($td);
Demo here: http://jsfiddle.net/edgarinvillegas/r2Bca/3/
Upvotes: 2