Charles Yeung Charles Yeung - 11 days ago 6
Javascript Question

JavaScript/jQuery - Get text and translate it

Is it possible to use jQuery to get a text from an element and translate it to other languages?

Before

<p>Hello</p>


After

<p>bonjour</p>

Answer

Use Google translation API. Easy to use. The following translates Spanish to English. To translate from and to other languages, simply change 'es' and 'en'

<div id="content"></div>

google.load("language", "1");

function initialize() {
    var content = document.getElementById('content');
    content.innerHTML = '<div id="text">Hola, me alegro mucho de verte.<\/div><div id="translation"/>';
    var text = document.getElementById("text").innerHTML;
    google.language.translate(text, 'es', 'en', function(result) {
        var translated = document.getElementById("translation");
        if (result.translation) {
            translated.innerHTML = result.translation;
        }
    });
}
google.setOnLoadCallback(initialize);

Check working example at http://jsfiddle.net/wJ2QP/1/

Comments