I got this code working but it feels clunky. I am wondering if there is a way I can improve it.
(I'm intermingling JavaScript and jQuery). I'm using jquery-1.11.1.min.js hosted on code.jquery.com.
JS:
<script>
$('#indices > div').each(function () {
var url = "http://query.yahooapis.com/v1/public/yql";
var $this = $(this);
var symbol = $this.attr('id');
var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol + "')");
$.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
.done(function (data) {
$this.children('#aname').text(data.query.results.quote.Symbol);
$this.children('#aresult').text(data.query.results.quote.LastTradePriceOnly);
$this.children('#apercentchg').text(data.query.results.quote.PercentChange);
$this.children('#adollarchg').text(data.query.results.quote.Change);
if (data.query.results.quote.PercentChange.indexOf("+") != -1) {
$this.addClass("divgreen");
$this.children('#apercentchg').className = "greenText";
} else {
$this.addClass("divred");
$this.children('#apercentchg').className = "redText";
}
});
});
</script>
HTML:
<div id="indices">
<div id="^GSPC">
<span>S&P 500</span><br>
<span id="aresult"></span> <span id="adollarchg"></span>
</div>
<div id="^NDX">
<span>Nasdaq 100</span><br>
<span id="aresult"></span> <span id="adollarchg"></span>
</div>
<div id="GLD">
<span>SPDR Gold</span><br>
<span id="aresult"></span> <span id="adollarchg"></span>
</div>
<div id="SLV">
<span>iShares Silver</span><br>
<span id="aresult"></span> <span id="adollarchg"></span>
</div>
<div id="^N225">
<span>Nikkei 225</span><br>
<span id="aresult"></span> <span id="adollarchg"></span>
</div>
<div id="^FTSE">
<span>FTSE</span><br>
<span id="aresult"></span> <span id="adollarchg"></span>
</div>
</div>
CSS:
<style>
div.indices {
font: 12px/19px Helvetica, Arial, sans-serif;
width: 825px;
margin: 0 auto;
}
.divgreen {
color: #000;
float: left;
background-color: #70DB70;
border-right: 3px solid #FFF;
padding: 3px;
}
.divred {
color: #000;
float: left;
background-color: #f7cdc2;
border-right: 3px solid #FFF;
padding: 3px;
}
</style>
Update Here is the final product of the great suggestions below and some additional changes. I also added a 'stretchy' ability that targets the parent container size and when that view able space gets to small to work with it hides the stock information bar. I did this to reduce clutter for mobile users.
http://jsfiddle.net/franktudor/LZm2f/
and it works like a charm and I hope someone else finds this useful for their website.