JavaScript/jQuery - Get text and translate it

Charles Yeung picture Charles Yeung · Mar 22, 2011 · Viewed 96.6k times · Source

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

mfernandes picture mfernandes · Nov 22, 2013

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