DOM Range & Selection

Try it out!

Change Text Color:
Change Text Size:
Change Font Family:
Translate Selection:
Find some sample text to play with below, from Bill Gates' speech at the MIX conference in 2006:

"So, the theme, as I said, is about using software to reach out and create a new customer experience, one that is valuable for the organization. This idea of both attracting customers from the very beginning, retaining them, making it easy for them to buy, make it easy to upsell them, building the community around them that draws in other customers, this is a very hot area. In fact, there's best practices all over the Web. I wouldn't say any one single Web site has all of these things brought together. People who have always thought of their Web sites as their key way to reach out to customers have been building that database, and for other companies the idea of how you merge the different experiences that you might have, gather that database, and personalize the experience based on things that happen outside of the Web, that's very important as well."
DOM Range provides developers a standard way to select a piece of a document and operate on it. The HTML5 Selection APIs allow this demo to extract the user selection - and the Range behind it - for modification.

When you select text and click a command, code like the following gets executed:

window.getSelection().getRangeAt(0).execCommand(translateBing, Range.COMMAND_TYPE_ASYNC, 'en', 'de')

Where execCommand() is a custom method defined off the Range prototype. Once the method gets the Range corresponding to your selection, it passes the nodes inside it to a callback, which in this case is the translation function. The callback modifies the nodes, which the method then re-inserts into the document; this process is made much easier by the fact that Range operates in terms of nodes to begin with.