My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
TranslateMethod  
$( ).translate([sourceLang,] destLang [,options])
Featured
Updated Mar 11, 2011 by balazs.endresz

List of available languages: http://code.google.com/apis/ajaxlanguage/documentation/reference.html#LangNameArray

If you don't specify a source language it will be automatically detected. But in many cases it's better to set that too. You can use the long name of the language or just the language code ('en' or 'english') and it isn't case-sensitive either.

$(function(){ //on document ready
  //to german from any language:
  $('body').translate('de');
	
  //from english to german:
  $('body').translate('en', 'de');
	
  //with options:
  $('body').translate('de', { toggle: true } );
  $('body').translate('en', 'de', { toggle: true } );
  
  //you can set the languges in the options too (setting as a separate parameter like above overrides it):
  $('body').translate( { from: 'en', to: 'de', toggle: true} );

  //as of v1.4 you can also pass a complete callback as the third argument:
  $('body').translate('en','de', function(){ alert("complete"); });
})

Options

Override defaults with $.fn.translate.defaults:

  $.fn.translate.defaults = { returnAll:true };
  //or
  $.fn.translate.defaults.returnAll = true;

These are the default values after each option:

  • fromOriginal: false / default changed to true in v1.4 /
    • use only if you have specified a source language
    • if you have translated elements to a language and want to translate them again this will force the plugin to use the original text (from the language you specified to translate from) as the source text
    • toggle and data will be true automatically
  • toggle: false
    • true: all translation will be cached (stored with $.data) and used if it's found, or translated to otherwise
    • if the text on the page doesn't change you can set it to true: this will return the translation immediately if it was stored before
  • async: false
    • this prevents the browser from freezing on larger sites by executing each DOM filtering iteration with a delay (it doesn't affect the request sent to Google)
    • you can set the length of the delay in ms, setting it true means 2 ms
    • the returnAll option won't work, it will return the jQuery object immediately
  • data: true
    • store source and translated text with $.data
    • $(el).data("translation")[langCode][type] where type is either "html" or the name of an attribute:
    • $("p").data("translation")["en"]["html"] or $(":input").data("translation")["en"]["value"]
    • changed in 1.4.0: "$val" and "$html" is used instead of "value" and "html" ("attribute" can be used more safely)
  • walk: true
    • true: finds elements having textnodes and translates only their content; on very large and complex pages this might take some time (see the async option)
    • false: translates the given elements' .html(), generates more requests
    • this requires the jQuery.fn.nodesContainingText plugin (included along with other modules)
  • returnAll: false
    • true: returns all elements, which have textnodes (see the walk option)
    • using .end() after this returns the caller object
    • false: returns the caller jQuery object
  • not: ""
    • selector - elements to leave out (script, noscript, style, object and iframe elements will be omitted either this is set or not)
    • doesn't work for elements having textnode siblings, as the whole content of their parent node will be translated (see the walk option),
    • in this case, you have to add a notranslate class to those elements before the translation: $(selector).addClass("notranslate"); $("body").translate(...);
    • alternatively you can use the .translateTextNodes() method instead, see: TextnodeTranslatorIntegration
  • replace: true
    • replace original text on the page with the translation
  • rebind: true
    • rebind event handlers for elements translated as html (see the walk option)
  • subject: true
    • if some text is given, only that html attribute will be translated
  • altAndVal: true
    • translate alt and :button,:text,:reset's value attribute too when translating text/html
    • these don't have any textnodes, so they can be processed along with other nodes if the subject option is true
  • setLangAttr: false
    • store destination language code in the html lang attribute for each element
    • true: set the 'lang' attribute
    • false: don't set any attribute
    • string: set that html attribute
  • comments: false
    • removed in v1.4
    • true: translates comments too when an element's .html() is tranlated,
    • false: removes the comments, when an element's .html() is tranlated
    • comments might be only translated if they have textnode siblings (see the walk option)

options added in v1.4

  • stripWhitespace: true
  • stripScripts: true
  • stripComments: true
  • limit: 1750
    • here you can specify how long the url-encoded text should be that is sent to the Language API
    • the whole url must be less than 2000 characters long including the domain name and other parameters
    • you can increase this value slightly, but if it gets too large some requests will fail
  • separators: /\.\?\!;:/
    • a regex that specifies the end of a sentence
  • parallel (added in 1.4.3)
    • requests can be sent in parallel to speed up the translation
    • false or zero: requests are sent after each response is recieved
    • true: requests are sent all at once (can hang larger pages)
    • number: the delay in milliseconds after each request is initiated
  • trim: true (added in 1.4.7)
    • the translation always contains some extra whitespace which is removed by default with $.trim, setting this option to false keeps the spaces
  • alwaysReplace: false (added in 1.4.7)
    • by default if the translation is in the same language as the current text, then it's not replaced (see  issue #38 )
    • most likely you also have to set toggle: false, fromOriginal:false

Callback functions

These are passed to the options too. You can use the internal methods after this inside these, and the object's properties are also available:

  • this.i //the index of the current element
  • this.elements (array) // filtered elements, this.elements.end() returns the caller object (unfiltered)
  • this.translation (array)
  • this.source (array)
  • this.options
  • this.from //langCode
  • this.to //langCode
  • $('body').translate('en', 'de', {
      each: function(i){
        console.log( this.translation[i] ) // i==this.i
      }
    })
  • start: function(){}
    • arguments: elements (jQuery object), from, to, options
    • these are the filtered elements if the walk option was true (use .end() to return the original set)
    • v1.4.0: arguments: filtered elements, source, from, to, options
  • error: function(){}
    • google's results.error object will be passed (an error stops the script completely)
    • if you stop the translation with the internal stop() method it returns {message:'stopped'}
  • each: function(){}
    • executes after each element was translated
    • arguments: i, DOMelement, translation[i], source[i], from, to, options
  • complete: function(){}
    • arguments: original elements, filtered elements, translation (array), source (array), from, to, options
    • v1.4.0: the original elements object was removed, use elements.end() instead
    • the from argument is the sourceLangCode from the last part of the translation (if it was detected then that one)
  • onTimeout: function(){}
    • the requests won't be aborted automatically (use this.stop() inside it if you want to stop it)
    • arguments: filtered elements, from, to, options
    • v1.4.0: arguments: filtered elements, source, from, to, options
    • use elements.end() to get the original set of elements
  • timeout: 0
    • time after the onTimeout will fire (in ms)

In the comment below you may notice the copyEvents plugin: this is no longer needed, a bit different function is included in the plugin.

Comment by fred.chr...@gmail.com, Sep 10, 2008

Hi,

Many thanks for your response on the official Jquery Issue.

I'm sorry, but I've some trouble with the 'replace' option. I'm a beginner in JS (it's not a shame or an excuse ;) ) and I would like to learn the "how-to".

There is a sample code :

<html>
<head>
    <script type="text/javascript" src="js/jquery/jquery-1.2.6.min.js"></script>
    <script type="text/javascript" src="js/jquery/plugin.translate.js"></script>
    <script type="text/javascript">
    	$(document).ready(function(){	
			// translate to english all ID col*
			$('#translationEN').click(function(){
								$('[@id*=col]').translate('en', {
								start: 		function(){$('#translationProgress').show()},
								complete:	function(){$('#translationProgress').hide()}
								});
			});		
						
			// I would like to comeback to the original text, but... i don't understand how to proceed :/
			$('#translationFR').click(function(){
								$('[@id*=col]').translate('', {
								replace:	false // Uh :| I suppose it's not the good way...
								});
			});
		});
    </script>
</head>
<body>

<div id="translate">
	<a href="#" id="translationFR">FRANCAIS</a> | <a href="#" id="translationEN">ENGLISH</a>
    <span id="translationProgress" style="display:none">Translation in progress, please wait...</span>
</div>

<div id="col-1">Ce plugin est vraiment pratique et simple d'utilisation.</div>
<div id="col-2">Je félicite son auteur !</div>

</body>
</html>

Thanks in advance for your explanation. Best regards.

Comment by project member balazs.endresz, Sep 10, 2008
function toggleTransl(el, to){
  var $el=$(el),
    a=$el.data('translation.'+to+'.html'),
    b=$el.data('translation.'+to+'.value');
  if(a)
    $el.html(a);
  if(b)
    $el.val(b);
}

If you set data:true (stores the original text and translation) then you can use this function to toggle to a language that was translated before. So this goes inside your click event:

$('[@id*=col]').find('*').andSelf().each(function(){
  toggleTransl(this, 'fr')
});

I hope this will work! (Such functionality will be definitely included in a future release.)

Comment by fred.chr...@gmail.com, Sep 11, 2008

Hi,

Your function work very well with data:true. It's very powerful :] This Jquery plugin is a great job, I'm impressed, really.

A $().untranslate([sourceLang,] destLang[,option]) function in the future ? ;) I hope too ;)

Many thanks !

Comment by project member balazs.endresz, Sep 12, 2008

Thanks! I'm glad you like it! I've just implemented a toggle option that will automatically do this, but it will be only available in the next release. It has been pretty much refactored and needs a bit more testing, but hopefully I can post it in about a week.

Comment by fred.chr...@gmail.com, Sep 14, 2008

Great. I've put the toggleTrans() in your lib until your futur release. I keep an eye on it ;)

Comment by project member balazs.endresz, Sep 22, 2008

In v1.2.x you just have to set the toggle option, and you can restore any translation that was stored before (i.e. only if the data or toggle option was true when it was translated).

$(selector).translate( destLang, {toggle:true} );

Another important change is that $.translate.ready=function(){ ... } won't work, use $.translate().ready( function(){ ... } ) instead! But in most cases it's not necessary, so it's enough to put the code in $(document).ready().

If you are using a method of $.translate() put it in $.translate().ready() too. Some examples:

$(document).ready(function(){
  $('body').translate('english');
    //this will work 
    //returns a jQuery object and translates the text when the Language API is loaded

  $.translate( 'some text', { complete:function(){} } );
    //this will work too
    //returns an internal object and translates the text when the Language API is loaded

  $.translate().getLanguages();
    //this won't (always) work!
    //the Language API may not be loaded, the return value cannot be determined

  $.translate().ready(function(){
    $.translate().getLanguages() //this will work
  })

})
Comment by ag...@21productions.com, Sep 24, 2008

Been using this for click and translate and it's amazing! I have been having a problem getting it to work on load though without clicking (Would be perfect if I could get it to just do a simple translate of a large paragraph after the page loads). Here's what I've been trying with (the click works, but the on page load doesn't):

<html> <head>

<script type="text/javascript" src="jquery-1.2.6.min.js"></script> <script type="text/javascript" src="jquery.translate-1.2.1.min.js"></script> <script type="text/javascript">
function google_translation(from,to){
$('#test').translate(from,to, { not: 'select' })
}
</script> <script type="text/javascript">
$(document).ready(function(){
$.translate.ready=function(){
google_translation("en,"es");
}
})

</script>

</head> <body>

<input type="button" onclick="google_translation('en','es');" value="Translate "/>

<div id="test"> LOTS OF CONTENT HERE </div>

</body> </html>

Comment by project member balazs.endresz, Sep 24, 2008

In v1.2 you don't need the ready function for such thing (which was changed too). Just read the comment above :)

Comment by ag...@21productions.com, Sep 24, 2008

Played around with the different examples on your post above, and finally got it to work like a charm. Amazing work, kudos!

Comment by www.gree...@gmail.com, Nov 4, 2008

I use a drop down menu to choose the language:

	<select id="langsel" name="selector">
			<option  value="">Select a language</option>
			<option  value="fr">French</option>
			<option  value="de" >German</option>
			<option  value="el">Greek</option>
		</select>

and in the head I put

		$('#langsel').change(function(){
			$('div#container').translate( 'en', $(this).val(), {
				not:		'select', 
				async: 	true,
				toggle:	true
			})
		})

to translate the contents of the div with id="container".

When I choose a language for the first time e.g. french the result is correct but if I want to translate the text again to a different language e.g. greek the result is a combination of words in both languages greek and french. What am I doing wrong?

Comment by project member balazs.endresz, Nov 4, 2008

I presume you are using the latest version (1.2.x), the toggle option isn't available in 1.1.x. But it's a good question, as it translates from the current language unless the desired translation is in cache. I used to reload the page with history.reload() to get back to the original text, but now you can do that with "translating" back to the original language before the actual translation:

$('#langsel').change(function(){
  $('div#container').translate( 'en', { //revert to english first
    not: 'select', 
    async:  false,
    toggle: true,
    returnAll: true
  })
  .translate( 'en',  $(this).val(), {
    not: 'select', 
    async:  true,
    toggle: true,
    walk: false
  });
})

Note, that the async option is set to false when reverting the translation, it might work with async:100 but browsers can't delay execution precisely (Firefox 3 might be doing it well, but in other browser it's not guaranteed to work). So if async isn't set to false the languges in each element can be mixed up.

And another trick: these above are chained: you can do that due to the options added to each one (the first one returns all textnodes: returnAll:true so the second one doesn't have to parse the DOM again, and it's forced not to do that by walk:false ). But it's not necessary, just a bit speedup.

Also, there could be another option to use a language in the cache to translate from, so that you don't have to restore the translation manually -- I think that goes to the next release.

Comment by ag...@21productions.com, Nov 5, 2008

Translation has been working GREAT for most of the languages/pages I've been doing for big text in the thousands of characters. I did run into a problem that the translation works for chinese (zh) but not for chinese simplified (zh-CN) or traditional (zh-TW). Is it possible to use traditional? Really need it for a certain website.

Comment by project member balazs.endresz, Nov 6, 2008

In the function that converts to language code I expected all language codes to be lowercase, which they're apparently not. It only affets 1.2.x because it accepts whole language names as well, not just language codes like: $(...).translate('chinese'). Now fixed in v1.2.3.

Comment by aboost...@gmail.com, Nov 6, 2008

This looks very promising for my needs, but I'm finding that it conflicts with the Prototype library. It works fine if I don't include Prototype, but when I do, I get an 'object is undefined' error on line 725 of the 1.2.3 build. Any ideas?

Comment by project member balazs.endresz, Nov 7, 2008

Interesting, the full 1.2.3 is "only" 703 lines long. I also tried it with Prototype and it seems to be working fine. Maybe a link to the site?

Comment by aboost...@gmail.com, Nov 7, 2008

Thanks for the quick reply. It turns out that it was a conflict with scriptaculous, not prototype. I can probably work around that easier, so that's okay. I do have a different problem now. The translation seems to stop midway through the page that I'm trying to translate. You can see it here: http://boostani.dev.wiserearth.org/user/Honore login: soldemo password: demo

If you select Spanish from the Other Languages menu in the top right, then it should translate everything under the gray header, but it stops toward the end of the left navigation bar. Is this a Google limitation, or is the javascript running into problems?

Comment by project member balazs.endresz, Nov 8, 2008

I looked into it and it seems that Adblock Plus (a Firefox plugin) causes the API to fail silently if you have some specific words in the text: in this case it is "responsible" in $('div#view_relation') on your site (this is where the translation actually stops for me). Sounds weird doesn't it? Here's a small script I tested in other browsers and Firefox 3 with Adblock disabled and this way it's working, but not with Adblock:

google.language.translate("responsible",'en','es',function(r){console.log(r.translation)})

I experienced this with Firefox 2 too, but it disappeared when Firefox 3 came out, now it's here.

But it's not everything: if you want to translate $('div#view_relation').html() you get a bad request error:

var t=$('#view_relation').html().substr(0,2000); //without the word "responsible"
//.substr(0,2500) with Adblock -> nothing happens, no error, no request
google.language.translate(t,'en','es',function(r){console.log(r.translation)})

But on your site it's working if you diasble Adblock: at least it sends all the requests, but there seems to be a problem when the plugins tries to replace the text. But by manually replacing the content we can get the whole page translated:

var t, j=jQuery('#page').translate('en','es',{returnAll:true, limit:1000, 
  each:function(){  t=this; },
  complete:function(){
    var tr=jQuery(t.rawTranslation)
    j.each(function(i){
      jQuery.translate().replace(jQuery(this), tr[i], {replace:true, rebind:false})
    })
    jQuery('#indicator').hide()
  },
  start:  function(){   jQuery('#indicator').show() },
  error:  function(){   alert('error')   }
})

So this is a bug in the plugin, but now I don't really now what on earth causes it to fail on this text. The jQuery.translate().replace() in the script above is an internal function that replaces the content but somehow it doesn't seem to work automatically, and without the rebind:false option it fails too. But if you call it manually on complete it works.

Comment by project member balazs.endresz, Nov 8, 2008

Oh, and one more weirdness: google silently raised the character limit to 5000: http://code.google.com/apis/ajaxlanguage/terms.html but I never managed to get it working above about 1000: it returns two new types of errors: sometimes a response with 200 OK header containing an error message, and sometimes "XML tag name mismatch (expected meta) </head>\n". So be careful when raising the limit above 1000!

Comment by insitudi...@gmail.com, Jan 28, 2009

Hello! The plugin is great! Thanks! I have a problem, I need to set a cookie to mantain the language through different pages, can you help me with this..?

Here's my code:

<script type="text/javascript"> jQuery(function($){

$('#language').change(function(){
$('body').translate( 'es', {
not: 'select', async: false, toggle: true, returnAll: true
}) .translate( 'es', $(this).val(), {
not: 'select', async: true, toggle: true, walk: false
});
})

}) </script>

and the html:

<form>

<select id="language" name="selector">
<option value="es">Español</option> <option value="en">English</option>
</select>
</form>

Thanks in advance!

Comment by project member balazs.endresz, Jan 28, 2009

Hello, here's an example showing how to do that: http://jsbin.com/ofema/edit I've just put this to the Links section on the main page.

The way you do it in your example isn't necessary any more, it's handled by the fromOriginal option, as you can see that in the example.

Comment by insitudi...@gmail.com, Jan 29, 2009

Thank you!

Comment by kenji%lo...@gtempaccount.com, Feb 9, 2009

Hello, I need a help on how to use "$.data".

I'm trying to get this script to work. But, I get nothing in "#translated". Do you have any idea about what' wrong with this ? If I use this.translation0?, then it works, but I want to get html tags as well.

$(document).ready(function(){

	$("#translate").click(function(){
		$('#original').translate('en', 'ja', {
			data: true,
			replace: false,
			complete: function() { $('#translated').html($(this).data('translation.ja.html'));}
		});
	});
});
</script>
</head>
<body>
	
<div><a href="#" id="translate">Translate</a></div>
<div id="original"><ul><li>Hello</li></ul></div>
<div id="translated"></div>
Comment by project member balazs.endresz, Feb 10, 2009

The this inside the callback functions refers to the current object, not to an element. You can get the original element by the first argument, but that doesn't contain any data only if you set walk:false because by default the data is attached to each element containing text not the root element. So you could do this:

walk:false,
complete: function($elems) { 
  $elems.html( $elems.data('translation.ja.html') );
}
Comment by kenji%lo...@gtempaccount.com, Feb 10, 2009

Thanks, balazs. It worked!

Now, there is another problem. not: doesn't work anymore. I guess it's because of walk:false. There are parts in the text I don't want to translate. What would be the best way to handle this?

Comment by project member balazs.endresz, Feb 10, 2009

Sure!

$("#translate").click(function(){

$('#original').translate('en', 'ja', {
data: true, replace: false, not: '', complete: function($elems, $elemsAll) {
$elemsAll.each(function(i){
$(this).html( $(this).data('translation.ja.html') );
});
}
});
});

Comment by kenji%lo...@gtempaccount.com, Feb 11, 2009

Thanks for the quick answer, balazs.

I tried the code above but it seems to behave like replace:true, that is, the translation goes to the same location as the original text. I want to place the translation to a different location.

So, I tried the code below with and without walk:false, but it didn't filter tags specified with not:.

$elemsAll.each(function(i){
    $("#translated").html( $(this).data('translation.ja.html') ); 
}); 
Comment by project member balazs.endresz, Feb 11, 2009

Ah, ok, that makes more sense :)

The not option won't work in cases like when you want to exclude all anchor tags from some text in a paragraph because then the whole paragraph will be translated. The code below translates the innerHTML of #original and puts the translation to #translated but nothing could be removed:

$("#translate").click(function(){
  $('#original').translate('en', 'ja', {
    walk: false,
    replace: false,
    complete: function() {
      $('#translated').html( this.translation[0]  );
    }
  });
});

What you can do is to clone $('#original'), remove the elements you don't need and translate it afterwards:

$('#original')
  .clone()
  .find('*')
  .each(function(){
    if(this.tagName==='A') //could be $(this).is("a") but that can be much slower on many elements
      this.parentNode.removeChild(this);
  })
  .end()
  .translate('en', 'ja', {
    walk: false,
    replace: false,
    complete: function() {
      $('#translated').html( this.translation[0]  );
    }
  });

Hope that works!

Comment by support%...@gtempaccount.com, Feb 17, 2009

Thanks, balazs! I will try what you suggested.

Comment by project member balazs.endresz, Mar 12, 2009

Hi, it's 'translation.ru.html'!

Comment by ronck...@gmail.com, Apr 26, 2009

I'd like to take a page in spanish, and produce a new page with each spanish paragraph being followed by the same paragraph in english. If I use the replace:true option, I just get the english only. Has anyone done this? I can translate the spanish one <p> </p> at a time, but how do I put the translated english paragraph below the spanish paragraph?

Comment by project member balazs.endresz, Apr 26, 2009

Try it with these options:

replace: false,
each: function(i, el, tr){
  $(el).clone().html(tr).insertAfter(el);
}
Comment by ronck...@gmail.com, Apr 26, 2009

wow thanks, that worked just fine!

Comment by javier....@gmail.com, Apr 29, 2009

Hi:

How i can hide original text and show when is translated?

Comment by project member balazs.endresz, Apr 29, 2009

@javier.tia: I'm not sure if you meant something else but the examples at the top of this page do just that!

Comment by javier....@gmail.com, Apr 29, 2009

that is right, i look after comment and i found it the answer. Thank you.

Comment by nimesh1...@gmail.com, May 6, 2009

Hi,

I have a text that I would like to translate in russian. The text has custom tags and has multiple <BR> tags. The API behaves weird with <BR> tags. Are there known issues with <BR> tags.

Text to be translated:

<INPUTANSWER PARTID='1'>&nbsp;<IMG SRC='its://Workshop/ADSK Cert Exams (External)/2010/Sample Translations/INV10.P.07.01c.gif' SIZE='0' SRC_CETEMP="../item_shared/getresource.aspx?cmd=media&amp;urid=r5796927/ENU"><BR><BR><P>Open the file&nbsp;<I>DP-LCD-17.iam</I>. Follow these steps.</P> <P STYLE="MARGIN-LEFT: 0.5in; TEXT-INDENT: -0.25in">1.<SPAN STYLE="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>Place a <STRONG>90 degree</STRONG> explicit angle constraint to the inside faces of <STRONG>DP-1007:1 </STRONG>and<STRONG>DP-1006:1</STRONG> as shown.</P> <P STYLE="MARGIN-LEFT: 0.5in; TEXT-INDENT: -0.25in">2.<SPAN STYLE="FONT: 7pt 'Times New Roman'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>Drive this angle constraint between <STRONG>90 and 100 degrees</STRONG> with an <STRONG>increment</STRONG> <STRONG>of 0.125 degrees.</STRONG></P> <P>&nbsp;</P> <P>At what angle is there first interference?&nbsp;<ANSWER ID='1' SIZE='6' TYPE='2'></P><P>&nbsp;</P></INPUTANSWER>

Thank you for your help in advance, -Nimesh

Comment by project member balazs.endresz, May 6, 2009

@nimesh1983: What happens exactly?

Sometimes inline tags can be messed up during the translation because it's not always possible to determine where they should be in the text in an other language. That's what happens if you try the ui extension example: http://code.google.com/p/jquery-translate/wiki/Extensions further explained in the comments there.

But in your case the problem might be only that you don't close the br tags properly, they should look like this: <br/>!

Comment by nimesh1...@gmail.com, May 6, 2009

Ihave

//Make sure that the language api is loaded $.translate().ready(function(){
//Make sure that the language is translatable
if($.translate().isTranslatable(targetLanguageCode))
{
$('#TexttobeTranslated?').translate('en',targetLanguageCode, {data: true, replace:false,walk:false,not:'BR', complete: function(){

$('#TexttobeTranslated?').data('translation.'+targetLanguageCode+'.html'); }

When I try 2 translate text above, i don't get anything back. Thanks!

Comment by nimesh1...@gmail.com, May 6, 2009

Also I get no translation back if I have something like

Text to be translated:

<div><span>what are you doing?</span></div>

Comment by project member balazs.endresz, May 6, 2009

@nimesh1983: The replace option is set to false, which means it doesn't modify the page at all, and in the callback you do nothing with it either.

I'll look into the other thing today, there seems to be some problem with parsing the translation.

Comment by project member balazs.endresz, May 7, 2009

@nimesh1983: Try the new (1.3.3) release, the issue with translating that small div should be fixed now.

Comment by nimesh1...@gmail.com, May 7, 2009

Thank you balazs for your quick response. I got 1.3.3 and it looks like it fixed it. Actually I am setting $('#TexttobeTranslated??').html($('#TexttobeTranslated??').data('translation.'+targetLanguageCode+'.html')); in the callback. I forgot to copy that. Thank you for your help, -Nimesh

Comment by ronck...@gmail.com, May 7, 2009

You helped me figure out how to put each paragraph of the translated text after the original text. Can you tell me how to make either the original or the translated paragraphs appear bold? In other words, how can I wrap it in <b></b> tags?

this is the example you gave me:

replace: false, each: function(i, el, tr){

$(el).clone().html(tr).insertAfter(el);
}

Comment by project member balazs.endresz, May 8, 2009

@roncking: .css("font-weight","bold")

Comment by ronck...@gmail.com, May 8, 2009

I'm sorry, but I don't understand how to use this. I want either the original text OR the translated text to be bold so that it's easy to see the transitions between the two. So where do I insert the .css("font-weight","bold")?

Comment by umair.ch...@gmail.com, May 17, 2009

Impressive work. I can now translate it into almost all languages mentioned on http://code.google.com/apis/ajaxlanguage/documentation/reference.html#LangNameArray. But when i try it for Urdu 'ur'. It does not work. Do you have any idea what is the reason? Arabic 'ar' is working fine which is almost same as Urdu language.

Comment by project member balazs.endresz, May 18, 2009

It's just not yet translatable:

google.language.isTranslatable("ur") -> false

or

$.translate.isTranslatable("ur") -> false

Comment by nimesh1...@gmail.com, Jun 4, 2009

Hey Balaz,

When I get the translated text back from API, It puts Jquery ID in HTML Tags. How do I remove it?

Example: <P jQuery1244131196711="10">

Was ist die häufigste Antwort auf die Multiple-Choice-Fragen? Ich denke, das ist ziemlich offensichtlich. Aktualisieren </P>

Thank you, -Nimesh

Comment by project member balazs.endresz, Jun 4, 2009

@nimesh1983: Those attributes are always present if you have any data or events associated with that element. You would have to go through all the attributes of the element and remove the one that starts with "jQuery". But before the translation they can't be removed this way because it would destroy possible data or events on the element. What I can think of is removing them with a regex from the string, which will be translated:

$("").translate("en", {
  start: function(){
    this.rawSource = this.rawSource.replace(/ jQuery\d+\="\d+"/, '');
  }
});

Actually it seems to be rather harmless, maybe I'll put in the next version.

Comment by nimesh1...@gmail.com, Jun 4, 2009

So Do I call this piece of code after the translation is returned from API? Thank you, -Nimesh

Comment by project member balazs.endresz, Jun 4, 2009

No, if you look at it closely, it's called in the start callback, it's just an extra option. It will remove the attributes before the translation but not from the DOM elements but from the text that will be translated.

Comment by nimesh1...@gmail.com, Jun 4, 2009

Thank you very much for your prompt response Balazs... -Nimesh

Comment by project member balazs.endresz, Jun 15, 2009

@jasonatthediamondstore: You can translate whatever you feel like. Naturally, this plugin doesn't depend on what selector you use or how many elements you want to translate. Maybe you might want to use the walk:false option, so that the divs' innerHTML will be translated and the each callback fires for these divs - by default (walk:true) it gathers the deepest nodes containing text.

Comment by project member balazs.endresz, Jun 15, 2009

Just use an event handler.

http://code.google.com/p/jquery-translate/wiki/Extensions and there's another example on the main page under the links section

Comment by project member balazs.endresz, Jun 15, 2009

1. Check the examples on the Extensions page, those are made with selects!

2. You mean when the translation is executed? Without a live example I can't say much about that.

Comment by project member balazs.endresz, Jun 15, 2009

I don't really understand this, but I guess you can have a look at the jQuery docs regarding DOM manipulation: http://docs.jquery.com/Manipulation

Comment by project member balazs.endresz, Jun 15, 2009

It'd be nice if you could send a link to that page (to my email in case it's not public). I'm very interested in any bug reports as most of the problems come up only with some specific content. I'd have a look at it by tomorrow at latest.

Comment by project member balazs.endresz, Jun 15, 2009

For example:

<div>

some text

<select>
  <option>English</option>
  <option>French</option>
</select>

</div>

In this case if you translate the div and exclude the select with not:"select" then it will be translated too, because the plugin finds the deepest elements containing textnodes, which here is the div, then translates it's innerHTML, which contains the select too. You have to either wrap the textnodes in a span or div, or move the select outside this div.

Comment by project member balazs.endresz, Jun 15, 2009

In this case you can exclude the select when translating the div:

<div>

<span> some text </span>

<select>
  <option>English</option>
  <option>French</option>
</select>

</div>

(but only if the walk option is true - it is by default)

Comment by project member balazs.endresz, Jun 15, 2009

balazs.endresz@gmail.com I'll have a look at it tomorrow, thanks!

Comment by albino.m...@gmail.com, Jun 26, 2009

I've removed the calendar part mentioned above for now until I can figure out what's wrong but I've also noticed that some pages just won't translate and I can't see a good reason that they won't. All the pages have similar headers and footers.. and on some pages it won't even translate the header part. Any idea why this happens (maybe the page is too long??)

Comment by albino.m...@gmail.com, Jun 26, 2009

I also sometimes get messages from IE asking if I want to stop the script as it is it slowing down the browser. It doesn't seem to be slowing down, though, but sometimes the messages keep popping up.

Comment by project member balazs.endresz, Jun 26, 2009

@albino.manso: I've deleted your previous comment, please don't post large chunks of html here, use pastebin or jsbin instead. Sometimes Google can mess up the html structure that leads to parsing issues in the plugin, but without a live page I can't really say much about these kind of problems, if your site is not public please send me an email and I'll have a look at it!

Comment by richard....@gmail.com, Aug 28, 2009

I'm trying to use the translator to translate text in a form for upload to a website but the text fails to translate. I'm using FCKEditor, but that isn't causing the problem as it also fails when using simple textboxes. Can you please help me see where I'm going wrong please. Here is my code:

function startTranslation(){
		$('#text_en').translate('es','en');
}
function copyTranslate() {
	var e = FCKeditorAPI.GetInstance('text_es'); e.UpdateLinkedField();
	document.getElementById("text_en").value = document.getElementById("text_es").value
	startTranslation();
	var f = FCKeditorAPI.GetInstance('text_en'); f.SetHTML(document.getElementById("text_en").value);
}

Any help would be gratefully appreciated

Comment by richard....@gmail.com, Aug 28, 2009

Hi,

It's OK, I managed to figure out a way using your examples on the TranslateFunction page. Here is the fixed code:

function startTranslation(fromlang, tolang, fromId, toId){
	var e = FCKeditorAPI.GetInstance('text_es'); e.UpdateLinkedField();
	var sourceText = $('#'+fromId).val();
	var f = FCKeditorAPI.GetInstance('text_en');
	$.translate(sourceText, fromlang, tolang, {
		start:          function() {   $('#throbber').show(); },
		complete:    function(translation) { $('#'+toId).val(translation); $('#throbber').hide(), f.SetHTML(document.getElementById("text_en").value) },
		error:         function() {   $('#throbber').hide()   }
	});
	 
}
Comment by vitorcurtis, Sep 30, 2009

Hi,

There is a problem when we use the option 'not:' and we have a text in html with no tag. Can anyone help me solve this problem?

$('body').translate('english', destLang, {
  not: '.jq-translate-ui, .notT',
  fromOriginal:true
});

<body>
<p>Hello!</p>
Hello
<div id="sel"></div>
</body>
Comment by project member balazs.endresz, Sep 30, 2009

Hi, I'm just coding the download builder for the newer version, which will optionally handle this case too, until then you can use this script with a filter function: TextnodeTranslatorIntegration. Though, you can't use all the option with it yet.

Comment by sagarv...@gmail.com, Mar 24, 2010

hi , i have a problem with translation.I have a rss feed url which is dynamically loaded in to page ..i want to convert that div content in to required language.i have both french and portugues,,, here my code below

function startTranslation()

{
var qs= getQuerystring("sc_lang");
var element=document.getElementById("google_translate_element"); if(element!=null) {
var text = document.getElementById("google_translate_element").innerHTML;
jQuery(document).ready(function() {
if(qs == "pt-BR") {
alert(qs);
//$('#google_translate_element').translate('en', 'pt', { fromOriginal: true } );
$('#google_translate_element').translate( { from: 'en', to: 'pt-PT', fromOriginal: true} );

} else if(qs == "fr-FR") {
alert(qs);

$('#google_translate_element').translate('en', 'fr', { fromOriginal: true } );
}
})
} }

but im unable to convert the langage ..

Please help me out

Comment by project member balazs.endresz, Mar 26, 2010

fromOriginal: true is not necessary, it's the default since 1.4, and it might be written like this: {{{{ $.translate.languageCodeMap["pt-br"] = "pt-PT"; $.translate.languageCodeMap["fr-fr"] = "fr";

$('#google_translate_element').translate('en', getQuerystring("sc_lang") ); }}}}

But other than that I can't say anything based on this code, maybe if you send the whole page with pastebin for example.

Comment by mar...@gmail.com, Apr 7, 2010

hello everybody

I am having a bad problem with <br> tags, I am translating this parragraph

<p id="ingles">hola<br><br>cómo estás?</p>

and it works perfectly on the translation, but loses the <br> tags when I do an alert of the content of that parragraph after it is translated, I just recieve plain text

also I have tried to change the way <br> tag is written, like <br/> and <br />, and the only thing I have managed was to get a result of "<br/><br/>hello how are you?"

can someone help me out to keep the <br> where they belong? :)

thanks in advance

Comment by project member balazs.endresz, Apr 7, 2010

@marckd: it's really hard to reliably determine the position of html tags inside sentences when translated to an other language: http://code.google.com/p/google-ajax-apis/issues/detail?id=149 But you can just use $().translateTextNodes() instead of $().translate() and this won't be an issue, though the translation might be a bit different.

Comment by simonteu...@gmail.com, Apr 23, 2010

Is it possible to define words that should not be translated oder should be translated in a other way?

Comment by project member balazs.endresz, Apr 23, 2010

You can disable the translation by adding a "notranslate" class: <span class="notranslate">this won't be translated</span> AND you should also add the not:".notranslate" option.

If you want to define some custom translation for certain elements, then you can do this:

$("#id").data("translation")[lang]["html" || "value"] = "my translation";

but only AFTER an initial translation to that language is completed, and then you have to translate it again. It will then retrieve these values for all the elements instead of actually translating them. Currently you can't do this before an initial translation because then the plugin should always check all the .data(...) values, which is usually unnecessary, though that might change later.

Comment by ivan.slaughter@gmail.com, Aug 7, 2010

Can i use this to translate a form label? base on lang string on html header?

Comment by project member balazs.endresz, Aug 7, 2010

@ivan.slaughter: If you can select the label with jQuery, I guess you can. But you have to extract the language from the html header yourself, though it's usually not a good idea to translate to some language without any permission/user interaction.

Comment by mini...@gmail.com, Sep 6, 2010

Hi balazs.endresz, I like your google translate project, it is really great. But I have also notice that somebody has ask why Urdu is not translatable in May 17, 2009. Up to now, Google has added Urdu in their translate.google.com Why "ur" still cannot not be translated? I am looking forward to your reply.

Thank you.

Comment by project member balazs.endresz, Sep 6, 2010

Hi, Urdu is currently not translatable via the Language API: http://code.google.com/apis/ajax/playground/?exp=language#is_it_translatable You can create a ticket here: http://code.google.com/p/google-ajax-apis/issues/list

Comment by mini...@gmail.com, Sep 6, 2010

@ balazs.endresz,

Thank you again. I will submit a ticket later on.

Comment by jkintz...@gmail.com, Nov 11, 2010

Hi balaz.endresz. I'm new to JS/jQuery and really only delved into it because I want to make use of your translation module. Right now I am just trying to get simple test code to work, with no success. Here is what I am currently attempting:

<html> <head>

<script type = "text/javascript" src = "js/jquery-1.4.3.min.js" /> <script type = "text/javascript" src = "js/jquery.translate-1.3.9.min.js" /> <script type = "text/javascript">
$(document).ready(function(){
$('body').translate( 'en', 'es' );
});
</script>
</head> <body>
<p>I'm excited to use the jQuery translate plugin!</p>
</body> </html>

I don't know what could be simpler than that. I have confirmed that JS is working, and tried it across a few different machines/browsers. I'm pretty certain that I'm missing something obvious, but can't see what. I can send you the page URL if you would like. Thanks!

Comment by project member balazs.endresz, Nov 13, 2010

@jkintzele: That should definitely work! Please send me the URL!

Comment by jkintz...@gmail.com, Nov 13, 2010

I thought so... glad I'm not losing my mind here. URL is:

http://usenet.kintzele.com/test2a.htm

Interestingly, I got this test working:

http://usenet.kintzele.com/test5.htm

But I really want to translate at the body level.

I really appreciate your help and you quick response!

John john@kintzele.com www.kintzele.com

Comment by project member balazs.endresz, Nov 14, 2010

@jkintzele: Your script tags are not well-formed, you have to have a closing tag even if you just reference a file: <script type="text/javascript" src="js/jquery-1.4.3.min.js"></script>. But they're correct in the second example.

Comment by jkintz...@gmail.com, Nov 14, 2010

Gurgh. Can't believe I missed that... my apologies.

Comment by project member balazs.endresz, Nov 14, 2010

No problem :) Also, the example on the main page under the links section might be a good way to start experimenting!

Comment by project member balazs.endresz, Dec 15, 2010

@igormeden: You can catch each translation with the each, and complete callbacks, and do what you want with them right there, but you can also access them afterwards: see the data option on this page.

Translating to multiple languages is basically very easy: you just call $().translate() for each one but with the replace:false option (though it might have to be true for one specific language). If you'd really like a callback when every translation is finished the you can use this extension, which I seem to have misspelled: http://code.google.com/p/jquery-translate/wiki/Extensions#paralell

However if the user changes the contents of the element that has once been already translated then you have to use the following options as well: alwaysReplace:true, toggle: false, fromOriginal:false.

Comment by dealerfront@hotmail.com, Dec 17, 2010

where does your api key go? maybe a silly question, but i thought you needed it.

Comment by project member balazs.endresz, Dec 17, 2010

You don't necessarily need an api key but you can supply one by calling $.translate.load(apiKey) after including the plugin.

Comment by h.verou...@free.fr, Feb 9, 2011

I was going the hard way till I found this component! Saves me a lot of time! Tnx.

However what I can't seem to get clear is how to reset the translated elements to the start value. The start value can be all kinds of languages so I can't say 'put it back to fr' as in the upper example. I simply want to reset it, no matter what.

Ofcourse no problem at all to create and reset via my own data() - store but as the component saves it allready somewhere I just would like to know where te go for the original value en to put it back, something like selection.translate("").

I downloaded version 1.4.7

Comment by project member balazs.endresz, Feb 10, 2011

@h.verou...@free.fr: If you really have know way to know what was the original language then you can try something like this:

//for each translation:
var originalLang;
$("body").translate(to, { complete : function(){
  originalLang = originalLang || this.detectedSourceLanguage;
}});

//then for restoring the original language:
$("body").translate(originalLang);

Unfortunately there's a low chance that this isn't going to work properly because this.detectedSourceLanguage is overridden after every translation request, which may result in having different source languages. It may be better to rely on the detectedSourceLanguage only from the first request, but currently that's not the case. However, you can also use the each callbacks to do this.

Comment by h.verou...@free.fr, Feb 10, 2011

I solved it by putting the original text in the nodes data-pool with clone(true) and if the user selects 'raw', I replace it back in the dom. Works, all events are connected etc.

The reason that I do not know the source is that my site has Polish, Dutch, French etc writers who may write in what ever language. I even have paragraphs inside a div with multiple languages. However these have a lang attribute set based on which I hide/show them. But I saw that the lang attribute is not used as data is send to the translate service? It should have the higest priority, higher than the transFrom value when calling translate.

Comment by project member balazs.endresz, Feb 11, 2011

@h.verou...@free.fr: If there's only one (unknown) language then my code above would work too, though .clone(true) is probably more reliable. But if you have multiple languages then you should translate them separately:

$("*[lang]").each(function(){
  var $el = $(this);
  $el.translate( $el.attr("lang"), to, options );
});

The plugin isn't designed to handle multiple languages in one translation for various reasons, but using the lang attribute to determine the original language may be a good thing. However, one problem is that by using the setLangAttr:true option the plugin would change the lang attribute, and then $el.attr("lang") would return a language which wasn't the original one, so then it would use an already translated text as source for another translation. But if you have multiple languages then you should tranlate them separately anyway, and if you're there then you can easily read the lang attribute yourself, as in this code above.

Comment by h.verou...@free.fr, Feb 11, 2011

Balazs wrote: The plugin isn't designed to handle multiple languages

Yes, I noticed that. What I now do is instead of

$(mySelection).translate(..) I do $(mySelection).each( function(){$(this).translate(..)})

Works very well! It's a good component, saved me a lot of time. When I first thought it over it looked much simpler and I was learning the hard way that there are lots of pitfalls. Your component works great! I just need to make the right calls :-)

Comment by arubadev...@gmail.com, Feb 12, 2011

Hi,

I have used this translation functionality on my site. It works fine for mostly all the pages.

Problem is for page with large amount of content. This involves large amount of js calls for translation which results in following error:

Firefox - Internal error:too much recursion I googled for its reason and i found that it's because of the stack size of firefox which is 3000. If it exceed this limit js calls are automatically aborted.

I am sure that it's not due to any recursion in my code because it works fine in chrome. I found that the stack size of chrome is nearly 21000 which i suppose is the reason for my code working fine in chrome.

Can anyone please tell me how to solve this problem?

Any help on this will be very much apprecicated as i am in urgent need to resolve this issue and i can't find any solution to this.

Comment by project member balazs.endresz, Feb 12, 2011

@arubadev...@gmail.com: You just have to use the async:true option! I'd like to improve on this later, i.e. to drop the stack frame only after a few hundred calls, not after every function call, as it happens with async:true right now. It takes much more time this way, but at least works.

@h.verou...@free.fr: "there are lots of pitfalls" - I could talk about that for hours :)

Comment by arubadev...@gmail.com, Feb 14, 2011

Thanks for ur help Balaz.

I have one more question:

Do I need to get any API key for using this and if yes how do I get it? I just want to be sure before implementing this functionality on the production site.

Comment by project member balazs.endresz, Feb 14, 2011

@arubadev...@gmail.com: You don't need an API key, the Language API works without it fine, but I think if you use one you are less likely to be blocked if you initiate a lot of requests from one IP. So you just have to call $.translate.load(apiKey) before any translation. It's non-blocking but you don't need any callbacks either because the translations are scheduled automatically (otherwise if you don't load it manually the plugin will do that on first use).

Comment by arubadev...@gmail.com, Feb 15, 2011

Where can I get this api key from and after that do I need to make any changes to my code except that for loading the api key before any translation?

Comment by project member balazs.endresz, Feb 15, 2011

@arubadev...@gmail.com: This is what a google search revealed to me: http://code.google.com/apis/loader/signup.html You don't have to make any changes at all, just call $.translate.load(apiKey) once somewhere.

Comment by arubadev...@gmail.com, Feb 16, 2011

Thanks Balazs

I want to ask u about async property. I want to set it true only for pages with large amount of content. Currently I have used an approximation reached by calculating the length of html content on pages on which translation was not working. Is there some better way to set this property to true for only pages with large amount of content? I mean is there any pre-defined limit or some way u can suggest that I can use to set 'async' to 'true' for those pages. I want to do this as it slows down translation and as was previously mentioned by u.

Comment by project member balazs.endresz, Feb 16, 2011

@arubadev...@gmail.com: Probably the fastest way would be to just check $("body").html().length, but unfortunately you have now way of knowing how many calls will be necessary - maybe if javascript had dependent types :)

As an other solution you can also use the walk:false option which disables this expensive processing, and translates $(el).html() as it is, and also re-binds all jQuery based event handlers (unless rebind:false is set).

Comment by *piy...@colorsofbrain.com, Jul 15, 2011

hii i want to change my site content only to another language like from English to German how can i do that please help me ??

Comment by pmalbri...@gmail.com, Aug 17, 2011

I'm trying to convert my script to use bing. I include my id this way

jQuery.noConflict(); jQuery(document).ready(function(){

jQuery.translate.load("my bing id here");

})

When I run the script this is the error I get

$.ajax({url: "http://api.microsofttranslator.com/V2/Ajax.svc/GetLanguagesForTranslate", dataType: "jsonp", jsonp: "oncomplete", crossDomain: true, context: this, data: {appId: appid}}) is undefined

On This Error? data: {appId: appid}

If I include the bing id right after I include the Translate Script I get the same error. I can hard code the appid right into the translate script and I get the same error as well.

Any help would be appreciated.

Comment by pmalbri...@gmail.com, Aug 17, 2011

Ok, my above problem goes away when I upgrade from jquery 1.4.2 to jquery 1.6.2, however now I getting new errors:

My debugger is saying GL is undefined on this line:

return $( GL.getBranding.apply(GL, arguments) );

If you could please let me know which version of jquery works best with your code. I need to switch my code from Google to Bing is the next few weeks.

Thanks,

Comment by project member balazs.endresz, Aug 17, 2011

@pmalbri...@gmail.com: You are using $.translate.getBranding() which doesn't have a corresponding method in the Microsoft API -- as far as I know. So you can to drop that line of code anyway because it's not needed for the MS translator. But until the transition is complete I'd rather put it in a try-catch block instead. Please let me know if you have any problems, or even if it's working fine because I haven't got much feedback about it yet :)

Comment by Stephan....@gmail.com, Nov 9, 2011

I am trying to translate dynamically created pages with user posts where the posts can be in different languages. I know which possible languages the items can be in so what I am doing is I run the translation script on the entire page for each of these langauges. Each tim using a different "from" language. The problem is however that on the first run the plugin sets "lang=en" for all elements so for the subscequent passes it assumes all items are in English(this is at least what I think is going on). That results in none of the other language items getting translated. I have it set to fromOriginal:true which I thought would reevaluate all items and translate them on each pass if the source language is correct for that pass. can anybody help me resolve this issue?

Comment by project member balazs.endresz, Nov 9, 2011

@Stephan.Snoek: I did that for someone a few months ago: you have to detect the language for each block of text in different languages (or just store them with $.data), then translate them separately. The following script does that (with the Google API though), and also appends a translate button to each of these entries: http://pastebin.com/FTsQewnP I can help more in the weekend if you can send a page by email or somehow.

Comment by jone...@gmail.com, Jan 5, 2012

Hi there!

Would you have any recent example that uses a google translator api?

Thanks!

Comment by jone...@gmail.com, Jan 6, 2012

I have his but not working. Can anyone help?

<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script src="http://jquery-translate.googlecode.com/files/jquery.translate-1.4.7-debug-all.js"></script> </head> <body> test

</body> </html> <script type="text/javascript">

jQuery.translate.load("google translator api");

// $('body').translate('tl');

$('body').translate('fr');

</script>

Comment by building...@gmail.com, Apr 13, 2012

Need some help. I got the drop down menu to populate. When a language is selected. I get the alert, but the 'body' text does not change. Why...

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="http://jquery-translate.googlecode.com/files/jquery.translate-1.4.7-debug-all.js"></script>

$(document).ready(function(){ 
  
   jQuery(function($){ //when DOM is ready

   $.translate(function(){  //when the Google Language API is loaded
  
    function translateTo( destLang ){ 

    $('body').translate( 'english', destLang, {   
          not: '#language_dropdown', 
          fromOriginal:true
        });
		
    alert(destLang);
    }
            
    $.translate.ui('select', 'option')
      .appendTo('#language_dropdown') 
      .change(function(){    
        translateTo( $(this).val() );       
        return false;
      })      
  }); 
  });

Any help would be great. Thanks, MB


Sign in to add a comment
Powered by Google Project Hosting