Chris Tate-Davies

An archive of helpful tit bits of information for development, and probably some stuff that is incomplete, wrong or boring…

Javascript Language Translation

Posted on | March 18, 2010 | 2 Comments

On a project I am working on, I need to enable language translation. Thinking about it, turned into something quite complicated. But then I found the Google Language API which allows developers to hook into the Google Languages services.

So, I start a page – enabling UTF-8 character sets:

< meta content="text/html; charset=UTF-8" http-equiv="content-type">

And then hook into the Google API itself:

< script type="text/javascript" src="http://www.google.com/jsapi"></script>

Finally, a function that will pick up the text to translate. This function will automatically attempt to discover the source language for you.

< script type="text/javascript">
google.load("language", "1");

function translateLanguage() {
    var sourceText = document.getElementById("sourceText").value;
    google.language.detect(sourceText, function(lang) {
        if (lang.language != '') {
            document.getElementById('language').innerHTML = 'Source language: ' + lang.language;
            google.language.translate(sourceText, lang.language, 'en', function(result) {
                var translated = document.getElementById("translation");
                if (result.translation) {
                    translated.innerHTML = result.translation;
                }
            });
        }
    });
}
</script>
 

Comments

2 Responses to “Javascript Language Translation”

  1. vippi
    November 25th, 2011 @ 4:21 pm

    A interesting post right there mate ! Thanks for that .

  2. nytt kök
    November 25th, 2011 @ 5:32 pm

    extremely beneficial material, on the whole I imagine this is worthy of a book mark, thanks a lot

Leave a Reply