JavaScript/jQuery - Get text and translate it
Asked Answered
V

7

10

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>
Volant answered 22/3, 2011 at 7:39 Comment(2)
This is not a baked-in jQuery feature. You'd have to have some sort of translation API that you could call.Azotobacter
I wouldnt opt for automatic translation. It can lead to ugly misscommunication. From personal experience.Pragmatism
Z
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/

Zealous answered 22/3, 2011 at 8:3 Comment(2)
Fiddle is now broken.Denial
The Google translation API used in the Fiddle has been discontinued.Acknowledgment
C
15

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
Conjuration answered 22/11, 2013 at 14:29 Comment(1)
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!Cesena
Z
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/

Zealous answered 22/3, 2011 at 8:3 Comment(2)
Fiddle is now broken.Denial
The Google translation API used in the Fiddle has been discontinued.Acknowledgment
P
2

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

Pease answered 22/3, 2011 at 7:41 Comment(1)
Same answer. You need to load the google translation API and use it, I linked to the docs.Pease
D
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.

Diplodocus answered 22/3, 2011 at 7:45 Comment(0)
C
0

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

Campus answered 1/5, 2012 at 20:11 Comment(1)
I think bing translator does not exist anymoreWhiskey
P
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}
Portamento answered 23/11, 2016 at 16:34 Comment(0)
T
-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.

Titration answered 22/4, 2018 at 11:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.