11

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>
2
  • This is not a baked-in jQuery feature. You'd have to have some sort of translation API that you could call. Commented Mar 22, 2011 at 7:42
  • 2
    I wouldnt opt for automatic translation. It can lead to ugly misscommunication. From personal experience. Commented Mar 22, 2011 at 7:44

7 Answers 7

16

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
Sign up to request clarification or add additional context in comments.

1 Comment

I 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!
9

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/

2 Comments

Fiddle is now broken.
The Google translation API used in the Fiddle has been discontinued.
2

try google translate: http://code.google.com/apis/language/translate/overview.html

1 Comment

Same answer. You need to load the google translation API and use it, I linked to the docs.
1

You can use Google Translate's Javascript API.

<p id="some">Hello</p>
<input id="trans" value="Translate" type="button">

<script>
   $('#trans').click(function() {
     google.language.translate($('#some').html(), 'en', 'fr', function(result) {
         $('#some').html(result.translation);
     });
   });
</script>

You will need to load the js library in your page's HEAD section in order to use the API.

Comments

0

Use the Bing translator, since the free Google Translate API has been discontinued on December 1, 2011

1 Comment

I think bing translator does not exist anymore
0

On this PHP/JS solution you should use include PHP language files and set language on session/cookie not on $_GET. For the sake of simplicity I will do it on the

index.php file

<?php
$lang = $_GET['lang'];

if ($lang == 'fr'){
    $w = array(
        'Trouvé',
        ' non trouvé.',
        'Erreur. Veuillez réessayer.'
    );  
}else if($lang == 'en'){
    $w = array(
        'Found',
        ' not found.',
        'Error. Please try again.'
    );  
}else{
    $w = array(
        'Trouvé',
        ' non trouvé.',
        'Erreur. Veuillez réessayer.'
    );  
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
....................
<body>
....................
    <script type="text/javascript">
        /*  Translate JS
            Declare JS variables for translation in PHP file as below (Global vars outside $(document).ready). 
            Inside JS file call the variable as $.lang_mynamespace.var_name
        */
        $.lang_scan = { 
            found_js:"<?=$w[0];?>",
            not_found_js:"<?=$w[1];?>",
            error_js:"<?=$w[2];?>"
        };  
    </script>
</body>
</html>

JS file

$(function() {
    $("#scan_result").on('change', function(){

        //check number
        $.ajax({
            url: "check.php",
            dataType: "json",
            type: "post",
            data: {'scan_no': scan_value} ,
            success: function (response) {
                if (response.status == true){
                    alert("Scan no. " + response.scan_no + $.lang_scan.found_js);
                }else{
                    alert("Scan no. " + response.scan_no + $.lang_scan.not_found_js);                      
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
               //ajax error 
               alert($.lang_scan.error_js);            
            }
        }); 

    }); 
});

check.php return a json

{"scan_no": "123", "status": true/false}

Comments

-1

Why not try this:

var body = $("body");
var html = body.html();
var nhtml = html.split(" ");
var dict = [];
for (var i = 0; i < nhtml.length; i++) {
    nhtml[i].replace(dict[index]);
}

It can replace anything.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.