Skip to content

Instantly share code, notes, and snippets.

@johnrees
Last active January 2, 2016 02:49
Show Gist options
  • Save johnrees/8240034 to your computer and use it in GitHub Desktop.
Save johnrees/8240034 to your computer and use it in GitHub Desktop.
Ridiculously simple live currency conversion. I will make it into a jquery plugin soon but for now, if you put the convert.js snippet inside a jquery document ready tag it should just work™.
if $('span[data-currency]').length > 0
$.get '//query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22EURUSD%22%2C%20%22EURGBP%22%2C%20%22EURJPY%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=', (result) ->
$('span[data-currency]').each ->
matches = $(this).data('currency').match(/(\d+) (.+)/)
amount = parseInt(matches[1])
conversion = matches[2]
for conversions in result.query.results.rate
if conversion == conversions.Name
rate = conversions.Rate
return $(this).text Math.floor(amount * rate)
if ($('span[data-currency]').length > 0) {
$.get('//query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22EURUSD%22%2C%20%22EURGBP%22%2C%20%22EURJPY%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=', function(result) {
return $('span[data-currency]').each(function() {
var amount, conversion, conversions, matches, rate, _i, _len, _ref;
matches = $(this).data('currency').match(/(\d+) (.+)/);
amount = parseInt(matches[1]);
conversion = matches[2];
_ref = result.query.results.rate;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
conversions = _ref[_i];
if (conversion === conversions.Name) {
rate = conversions.Rate;
return $(this).text(Math.floor(amount * rate));
}
}
});
});
}
€500 is $<span data-currency="500 EUR to USD"></span>, £<span data-currency="500 EUR to GBP"></span>, <span data-currency="500 EUR to JPY"></span>¥
€500 is $681, £415, 71226¥
@johnrees
Copy link
Author

As promised, here is the jQuery plugin http://github.com/johnrees/cambio

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment