O'Reilly Hacks
oreilly.comO'Reilly NetworkSafari BookshelfConferences Sign In/My Account | View Cart   
Book List Learning Lab PDFs O'Reilly Gear Newsletters Press Room Jobs  


 
Buy the book!
Yahoo! Hacks
By Paul Bausch
October 2005
More Info

HACK
#26
Convert Currencies with One Click
Yahoo! Finance can tell you how many euros there are in a U.S. dollar, and a little JavaScript can speed up the answer
The Code
[Discuss (0) | Link to this hack]

The Code

This hack will let you highlight a currency amount on a web page and convert it from British pounds to U.S. dollars. It's a piece of JavaScript that resides in a browser bookmark, otherwise known as a bookmarklet. Bookmarklets run when you click the bookmark, and they can get information from the current page you're browsing. In this case, the information the bookmarklet gets is the currency amount you've highlighted.

The code for bookmarklets isn't very pretty to look at, so here's some nicely formatted JavaScript that approximates the bookmarklet functions:

	// Dissected JavaScript bookmarklet for one-click Currency Conversion

	// Set d to the document object as a shortcut
	var d = document;

	// Set t to the currently selected text, if available
	var t = w.selection?w.selection.createRange( ).text:w.getSelection( );

	// Test to make sure t is a number
	t = parseFloat(t);
	If (t != parseFloat(t)) {
		// If not, warn that the value isn't numeric
		alert('Please highlight a numeric value.');
	} else {
		// Build the URL
		var url = http://finance.yahoo.com/currency/convert?';
		url += 'amt='+escape(t)+'&';
		url += 'from=GBP&';
		url += 'to=USD';
		
		// And open in a new window
		window.open(url,
		'_blank',
		'width=480,height=440,status=yes,resizable=yes,scrollbars=yes');
	}

Because bookmarklets are compact, this is the actual code you'll need to use:

	javascript:d=document;t=d.selection?d.selection.createRange( ).text:d.
	getSelection( );t=parseFloat(t);if(t!=parseFloat(t)){alert('Please 
	highlighta numeric value.')}else{url='http://finance.yahoo.com/
	currency/convert?amt='+escape(t)+'&from=GBP&to=USD';void(window.open(url,
	'_blank','width=480,height=440,status=yes,resizable=yes,scrollbars=yes'))}


O'Reilly Home | Privacy Policy

© 2007 O'Reilly Media, Inc.
Website: | Customer Service: | Book issues:

All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.