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>

By admin

2 thought on “Javascript Language Translation”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.