Google API Showcase: The Live Translator

0
0



The API of Google has a lot of useful usage examples. This showcase demonstrates how we can use theGoogle AJAX Language API to build a live translator that allows us to translate text from one language into the other – and that almost on the fly.

Check out the demo here: DEMO

Here is the jQuery part:

(function($) {
  $.fn.translate = function(options) {
		 var opts = $.extend({}, $.fn.translate.defaults, options);
		 return this.each(function() {
			$this = $(this);
			$("select#_from option[selected]").removeAttr("selected");
			$("select#_from option[value='en']").attr("selected", "selected");
			$("select#_to option[selected]").removeAttr("selected");
			$("select#_to option[value='es']").attr("selected", "selected");
			$('#content',$this).val("");

			$(document).keypress(function(e){
				if(e.which == 13){
					$.fn.translate.initialize();
					$("#content").val("");
				}
			});
			$('#_from',$this).change(function(e){
				$.fn.translate.defaults._from_lang = $(this).val();
			});
			$('#_to',$this).change(function(e){
				$.fn.translate.defaults._to_lang = $(this).val();
			});
		 });
  };
  $.fn.translate.initialize = function() {
	  var content = $('#content');
	  var text = $("#content").val();
	  google.language.translate(text, $.fn.translate.defaults._from_lang, $.fn.translate.defaults._to_lang, function(result) {
	    var translated = $("#translation");
		var translated_original = $("#translation_original");
	    if (result.translation) {
	      (translated.html() != "")?translated.append("
"+result.translation):translated.append(result.translation);
		  (translated_original.html() != "")?translated_original.append("
"+text):translated_original.append(text);
	    }
		else{
		  (translated.html() != "")?translated.append("
"+text):translated.append(text);
		  (translated_original.html() != "")?translated_original.append("
"+text):translated_original.append(text);
		}
	  });
  }
  $.fn.translate.defaults = {
    _from_lang	: 'en',
    _to_lang	: 'es'
  };
})(jQuery);

Note that this is just a demo. Not all the languages that are supported by the Google AJAX Language API are included here.

Enjoy!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>