JavaScript/jQuery - Get text and translate it
111,670
Solution 1
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/
Solution 2
Use this JQuery plugin https://github.com/tinoni/translate.js
Disclaimer: I am the author
1 - Include the "trn" class to the text you want to translate:
<span class="trn">text to translate</span>
2 - Define a dictionary:
var dict = {
"text to translate": {
pt: "texto para traduzir"
},
"Download plugin": {
pt: "Descarregar plugin",
en: "Download plugin"
}
}
3 - Translate the entire page body:
var translator = $('body').translate({lang: "en", t: dict}); //use English
4 - Change to another language:
translator.lang("pt"); //change to Portuguese
Solution 3
try google translate: http://code.google.com/apis/language/translate/overview.html
Solution 4
Use the Bing translator, since the free Google Translate API has been discontinued on December 1, 2011
Author by
Charles Yeung
Updated on July 09, 2022Comments
-
Charles Yeung almost 2 years
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>
-
None over 13 yearsSame answer. You need to load the google translation API and use it, I linked to the docs.
-
Amar Singh over 8 yearsI think bing translator does not exist anymore
-
ryanjdillon over 8 yearsI needed a simple solution for a simple page that doesn't rely on cruddy translations by google translate, so this is preferred for me. Thanks!
-
Destaq over 3 yearsFiddle is now broken.
-
SaschaM78 almost 3 yearsThe Google translation API used in the Fiddle has been discontinued.