My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
Extensions  
Extensions
Featured
Updated Dec 13, 2011 by balazs.endresz

jquery.translate.ui

Simple extension to generate an element based on the translatable languages. You can try this here: http://docs.jquery.com/Main_Page by running it with Firebug ( http://getfirebug.com/ ).

$.getScript('http://jquery-translate.googlecode.com/files/jquery.translate-1.3.9.min.js', function(){ //when the script is loaded
  $.translate(function(){ //when the Google Language API is loaded

    $.translate.ui('select', 'option') //generate dropdown
      .change(function(){ //when selecting another language
        $('body').translate( 'english', $(this).val(), { //translate from english to the selected language
          not: '.option, #demo, #source, pre, .jq-translate-ui', //exclude these elements
          fromOriginal:true //always translate from english (even after the page has been translated)
        })
      })
      .val('en') //select English as default
      .appendTo('#jq-primaryNavigation'); //insert the dropdown to the page
    
    //insert Google's logo after the dropdown:
    $.translate.getBranding().appendTo('#jq-primaryNavigation');

  });
});

On other sites this will only work if jQuery was included before. Also, you have to append it to an existing element: .appendTo('h1') or .prependTo('body')

Since v1.4, you can also use a config object as the only argument, for example these are the defaults:

$.translate.ui({
  tags: ["select", "option"],
  //a function that filters the languages:
  filter: $.translate.isTranslatable, //this can be an array of languages/language codes too
  //a function that returns the text to display based on the language code:
  label: $.translate.toNativeLanguage ||
         function(langCode, lang){
           return $.translate.capitalize(lang);
         },
  //whether to include the UNKNOWN:"" along with the languages:
  includeUnknown: false
}).prependTo('body');

jquery.translate.progress

This small extensions helps you to integrate jQuery UI's progressbar component.

$(function(){ //DOM ready
  $('body').translate('de',{
    each: function(){
      this.progress("#progressbar" /* , options */ )
    }
  })
});

Available options to initialize the progressbar here: http://docs.jquery.com/UI/Progressbar/progressbar#options The progressbar will be automatically updated as each element gets translated.

Without arguments it will return a number between 0 and 100, with which you can manually update the progressbar component or just update some field on the page.

Official jQuery UI demo: http://ui.jquery.com/demos/progressbar/


Extensions added in v1.4.0

The translateLanguages function is currently included in the native extension was removed in v1.4.1, you can copy it from here.

Native language names

  • $.translate.nativeLanguages
  • $.translate.nativeLanguages = {
      "sq":"Shqipe",
      "ar":"العربية",
      "bg":"Български",
      "ca":"Català",
      "zh":"中文",
      "zh-CN":"简体中文",
      "zh-TW":"繁體中文",
      "nl":"Nederlands",
      "en":"English",
    ...
    ...
    };
  • $.translate.toNativeLanguage(lang)

paralell

  • $.translate.defer
  • $.translate.run

For example, this can be used to translate language names to the corresponding languages, then get a notification when it's all done:

function translateLanguages(languages, callback){
  delete languages.UNKNOWN;
  var deferred = []; //instances to be executed later are collected here
  $.each(languages, function(l, lc){
      if( $.translate.nativeLanguages[lc] ){ return; } //if there's already a translation
      
      var deferredInstance = 
               $.translate.defer( $.translate.capitalize(l), "en", lc, 
                         function(tr){ $.translate.nativeLanguages[lc] = tr; });
      deferred.push( deferredInstance );
  });

  if(!deferred.length) //if there's nothing to translate
    callback();
  else
    $.translate.run(deferred, callback);
}

//translate all translatable languages:
translateLanguages($.translate.getLanguages(true), function(){ alert("done") })
Comment by project member balazs.endresz, Nov 24, 2008

If you try the first example on http://docs.jquery.com you may notice that the last part of the page won't be translated, because there's an h2 element that contains this html:

<a href="/UI" title="UI">jQuery UI</a> Reference

and after the translation it becomes

<a href="/UI" title="UI">jquery UI-Referenz</a>.

I have no idea why this happens, but it will break the plugin as it stores the translation on the h2 element via $.data and after one translation it will search the inner element (the anchor tag) not the h2 and finds nothing as the translation was stored on it's parent.

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

Here's the bug report on the above issue, please give it a star: http://code.google.com/p/google-ajax-apis/issues/detail?id=149

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

I've just realized that Google has fixed this a while ago but oddly enough it has been replaced with a jQuery bug that caused almost the same error at exactly the same place on the page.

Now it's been fixed in the plugin: http://code.google.com/p/jquery-translate/issues/detail?id=10

Comment by fid...@gmail.com, May 21, 2009

Hi there,

Can i have a working sample on using progressbar extension?

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

Try it here by running the code below in Firebug:

$.getScript('http://jquery-translate.googlecode.com/files/jquery.translate-   *LATEST VERSION*   .min.js', function(){ 
  $.translate(function(){ 
    $.translate.ui('select', 'option') 
      .change(function(){ 
        $('body').translate( 'english', $(this).val(), {
          not: '.option, #demo, #source, pre, .jq-translate-ui', 
          fromOriginal:true,
          each: function(){
            this.progress("#progressbar");
          }
        })
      })
      .val('English')
      .appendTo('#dock');
    
    $.translate.getBranding().appendTo('#jq-primaryNavigation');

  });
});

If you switch back to English there's an error message, because the html structure changes during the translation (as described a few comments before). It's not so common at all but maybe I should make it fail silently, as there's nothing I can do with that. Anyway, it's unrelated to the progressbar.

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

Actually the problem here is slightly different: in the translation two spans with some text between them get merged into one span element. And there's another issue when the progressbar doesn't move if the translation is restored from $.data. I'm fixing these now.

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

Fixed in v1.3.7.

Comment by tatai...@gmail.com, May 26, 2009

I need to set a cookie to mantain the language through different pages and need to have different languages in a .ui('select','option') Live link: http://angelsinaction.tv/aia_tv.php Can you please figure this out? Thanx in advance.

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

@tataijal: Regarding the cookies check the example on the main page under the "links" section!

Using the UI extension with different languages is possible, but you have to override the $.translate.getLanguages function to do that, but it's not really a clean solution, and it will be addressed in the next major version. Now, I'd say you're better off with creating a new function by modifying the $.translate.ui function a little:

$.translate.myUI = function(a, b, c){
  var languages = $.translate.getLanguages(true, ["en", "de", "fr"]) //here you can filter the languages
  var str='', cs='', cl='';
  if(c){ cs='<'+c+'>'; cl='</'+c+'>'; }
  $.each( languages , function(l, lc){
    str+=('<'+b+'>'+cs+l.charAt(0)+l.substring(1).toLowerCase()+cl+'</'+b+'>');
  });
  return $('<'+a+' class="jq-translate-ui">'+str+'</'+a+'>');
}
Comment by tatai...@gmail.com, May 26, 2009

Sir, I checked the link with 'ul','li','a'. I just want this to be done with 'select','option'. Please help me.

Comment by tatai...@gmail.com, May 26, 2009

Sir, I'm also sending the code I tried with 'select','option': <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script> <script src="http://jquery-translate.googlecode.com/files/jquery.translate-1.2.6.min.js"></script> <script src="http://stilbuero.de/jquery/cookie/jquery.cookie.pack.js"></script> <script> jQuery(function($){ //when DOM is ready

$('body').css('height','900px');
$.translate(function(){ //when the Google Language API is loaded
function translateTo( destLang ){ //this can be declared in the global scope too if you need it somewhere else
$('body').translate( 'english', destLang, { //translate from english to the selected language
not: '.jq-translate-ui', //by default the generated element has this className fromOriginal:true //always translate from english (even after the page has been translated)
});
}
//you can generate other controls as well, not just a dropdown: $.translate().ui('select','option')
.appendTo('body') //insert the element to the page .css('background-color','white') .find('a') .attr('href', '#') //to change the mouse pointer .change(function(){ //when selecting another language
translateTo( $(this).text() );
$.cookie('destLang', $(this).text() ); // set a cookie to remember the selected language
return false; //prevent default browser action
})
var destLang = $.cookie('destLang'); //get previously translated language
if( destLang ) //if it was set then
translateTo( destLang );
}); //end of Google Language API loaded
}) //end of DOM ready </script>

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

@tataijal: If you are using a dropdown then you have to use .val() instead of .text() and the .find('a').attr('href', '#') part is unnecessary too, here's a corrected version: http://jsbin.com/exewe/edit

Comment by Shidi...@gmail.com, Jun 15, 2009

wow... nice project... but you know? I have some problems,

can I translate the <title> script with this translator?

tell me about this...

thanks

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

Of course: $("title").translate(...)

Comment by lompi...@gmail.com, Mar 10, 2010

I used your really precious code (..and suggestions) in my website http://www.takekerala.com. But, a part some discrepancies mainly caused by my poor coding skills, now I have a problem while trying to authomatically translate the javascript error messages generated by the wrong use of a normal form. They continue to appear in english as in the code itself. Since there are many possible errors and so many languages.. what can I do? ..please.. (and a big thanks!)

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

You can translate any text stored in a javascript object too, basically this is how you do it:

var msgs = {};
msgs.en = ["message1", "message1"];
$.translate(msgs.en, "en", lang, function(transl){
  msgs[this.to] = transl;
});

$("body").translate("en", lang);

Also, you could place the error messages in hidden divs as well, so they will be translated along with the rest of the page. And with the parallel extension you could translate them to all of the languages but that isn't necessary I guess.

Comment by eformx@gmail.com, Mar 25, 2011

Is it possible to translate the page based on the browsers preferred language. For example I create a site in English and they view it in Germany. It picks up the browser language and the body is updated. I can get the preferred language from the web server, but I was wondering if the plugin has the ability to do this natively (is it built-in)?

Thanks,

Rob

Comment by project member balazs.endresz, Mar 25, 2011

@eformx: It's not built in the plugin, but I would strongly discourage you from doing that, it's just an extremely irritating thing to do. A lot of people work in foreign speaking countries, or know many other languages besides their native one. This just can't be determined automatically. But if you had a good reason for it then I think inspecting the Accept-Language header may be a better choice than looking at the IP address. Here you can read more about these issues: http://webreflection.blogspot.com/2010/11/ux-vs-ip-based-language.html

Comment by eformx@gmail.com, Mar 25, 2011

@balazs: thanks for the tip! I agree with the comments. I am integrating your awesome plugin into my online Web Form Builder available at http://www.formthis.com

I have a good little write up on my blog which shows it off with a few screenshots! http://blog.formthis.com/post/2011/03/25/FormThis-Universal-Translator!.aspx

Thanks for your help! The plug-in will help many people!

Comment by eformx@gmail.com, Mar 29, 2011

@balazs: I am using this truncate plugin: http://www.examplet.buss.hk/jquery/truncator.php but when I click the more link the translation is lost.

I suppose a callback on the truncate plugin is required? or do you have another suggestion?

Thanks! Rob

Comment by project member balazs.endresz, Mar 30, 2011

@eformx: If the content changes on the page then the translation get really complicated. What I would do is the following:

1. clone all elements that need to be truncated 2. append them after the original 3. truncate the original 4. add show, and hide buttons for both 5. hide the clone 6. and for restoring the whole text: hide original, and show clone

This way both will be translated, and the content won't change during the translation, which is good.

Also there's a $.translate.truncate(text, limit) function built in this plugin, though the limit here means the length of the URL-encoded text, but that can be modified easily: http://code.google.com/p/jquery-translate/source/browse/trunk/src/jquery.translate-core.js#351 It's not perfect at all, but it might be useful.

Comment by eformx@gmail.com, Mar 30, 2011

@balazs: My final solution was to hide the truncated text and then fire the truncate plugin in the complete method. It works like a charm! Thanks again for the fast feedback!

Rob

The solution:

//hide the paragraph in document ready 
$(".formthis_truncate").hide();

//data is the language value returned from an asp.net webmethod, ie 'fr' for french 
$('.form1').translate( 'english', data, { not: '.option, .jq-translate-ui',
 fromOriginal:true, complete: function(){ 
 $(".formthis_truncate").trunc(200," [more...]", " [less...]").fadeIn(2000); } 
})
Comment by project member balazs.endresz, Mar 31, 2011

@eformx: I think hiding is not necessary in this case because it will be translated anyway.

Comment by Javier...@gmail.com, Sep 19, 2011

I've been searching a way to add some exceptions to the translate function, like adding a local tranlation of some words for example the string "Apartamentos en Mármoles" google translate it to "Apartments in Marble" and i dont want to translate Mármoles because it is the name of a village.

Anyone can help me?

Comment by project member balazs.endresz, Sep 19, 2011

@Javier...@gmail.com: Just add a "notranslate" class to the element, like this:

Apartamentos en <span class="notranslate">Mármoles</span>

Though I'm not sure if it's going to wotk with the Microsoft Translator back-end.

Comment by athe...@gmail.com, Dec 12, 2011

Hi,

I am using this and it was working fine but from last week its not working. If you know please let me now.

Comment by rlindab...@gmail.com, Dec 13, 2011

How do I set a default language in the drop-down using translate.ui v1.4.x? Has that been deprecated?

Comment by project member balazs.endresz, Dec 13, 2011

Yes, there's a note for that in the description, but I'm just going to change it to use the language code instead: .val("en")

Comment by nilesh.v...@gmail.com, Feb 2, 2012

Hello all, I had done following code for one site, it was running well before some days but today its not working at all. What should I change for running it?? plz help me.

<html xmlns="http://www.w3.org/1999/xhtml" > <head>

<title>Untitled Page</title> <link href="js/jquery.jgrowl.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="js/jquery1.4.js"></script> <script type="text/javascript" src="js/jquery.translate-1.3.9.min.js"></script> <script type="text/javascript" src="js/jquery.cookie.pack.js"></script> <script type="text/javascript" src="js/jquery.ui.all.js"></script> <script type="text/javascript" src="js/jquery.jgrowl.js"></script>
<script type="text/javascript">
jQuery(function($){ //when DOM is ready
$.translate(function(){ //when the Google Language API is loaded
function translateTo( destLang ){ //this can be declared in the global scope too if you need it somewhere else
$('body').translate( 'english', destLang, { //translate from english to the selected language
not: '#jq-translate-ui', //by default the generated element has this id fromOriginal:true, //always translate from english (even after the page has been translated)
not: 'select',
start: function() { $.jGrowl('<img src=ajax-loader.gif> Translating...', { life: 8000} ); }, complete: function() { $.jGrowl('Translated...'); }, error: function() { $.jGrowl('Error...'); }
});
}
$('ul')
.find('a') .click(function(){
var lang = $(this).attr('id'); translateTo( lang ); $.cookie('destLang', lang ); return false;
});
var destLang = $.cookie('destLang'); //get previously translated language
if( destLang ) //if it was set then
translateTo( destLang );

}); //end of Google Language API loaded

}); //end of DOM ready

</script>

</head> <body>

<form id="form1">
<div>
<ul>
<li><a href="#" id="English" title="English">English
</a></li>
<li><a href="#" id="Dutch" title="Dutch">Dutch
</a></li>
<li><a href="#" id="Hindi" title="Hindi">Hindi
</a></li>
</ul>
<div id="essay">
5000 words essay The Outline of Whites’ Violence Vs. Blacks’ Nonviolence in American History “I have a dream that one day on the red hills of Georgia the sons of former ...........” Mahatma Gandhi
</div>
</div>
</form>
</body> </html>

Comment by hoangtru...@gmail.com, May 2, 2012

img a herf ?>?>/

Comment by hoangtru...@gmail.com, May 2, 2012

img a herf to Icon ... ? http://hit.com.vn


Sign in to add a comment
Powered by Google Project Hosting