I am working on some JavaScript for a website with content in multiple languages. I would like to use the Google Translate API to allow the user to select a word (or phrase) and have a translation automatically provided. For the time being, I'm simply having it alert the result for testing.
This is what I have so far: google.load("language", "1");
function getSelection() {
var selection = (!!document.getSelection) ? document.getSelection() :
(!!window.getSelection) ? window.getSelection() :
document.selection.createRange().text;
if (selection.text)
selection = selection.text
console.log(selection);
return selection
}
$(document).ready(function() {
$(window).mouseup(function() {
var selection = getSelection();
if (selection != "") {
google.language.translate(selection, "", "en", function(result) {
if (!result.error) {
alert(result.translation);
} else {
alert(result.error);
}
});
}
});
});
The problem that I'm running into is that my getSelection() function is returning a Range objects, which is apparently incompatible with google's language.translate() function. All I really need is a way to retrieve the actual text from the Range as a string so I can pass that. As far as I know there's some really easy, obvious way to do this that I'm just missing (yes, I tried using selection.text), but my experience with JavaScript is limited and Googling it hasn't revealed anything useful.
Can anyone help?