views:

483

answers:

3

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?

+1  A: 

Try jQuery google translate - http://code.google.com/p/jquery-translate/.

Randal Schwartz
Oh nice, I'll definitely have to check that out! Thanks!
Josh Ourisman
+1  A: 

Unsurprisingly there was a really obvious answer that I just completely missed. selection.toString()...

Josh Ourisman
It's borderline, but you still deserve to grant yourself the infamous Questioner-Who-Had-Answer-But-Alas-Brain-Is-Tricky-Stuff ;-) +1 for you comment!
Morten Bergfall
+1  A: 

You can do something like this:

function getSelection() {
    var selection = window.getSelection ? window.getSelection() + ''
                                        : document.selection.createRange().text;
    return selection
}

By concatenating an empty string to the result of the getSelection() method, its value gets converted to string, it's a common short-hand, equivalent to call the toString method, because:

var test = {
  toString: function () { 
    return 'foo';
  }
};

test+'' == 'foo'; // true

You also don't need to use the double logical negation (!!) in a ternary, because the first operand, the condition, its automatically converted to Boolean.

CMS
Ah, good to know. Thanks!
Josh Ourisman