Click here to Skip to main content
Click here to Skip to main content

Google Language Translator Using jQuery

, 30 Oct 2011
Rate this:
Please Sign up or sign in to vote.
Multilingual support for applications using Google Translator and jQuery.

Introduction

This article is all about my experiences with one of the toughest jobs (initially) I was involved in, but it turned out to be one of the easiest ones, thanks to jQuery and jQuery-Translator which uses the Google Language Translator.

Background

The requirement was stated in very simple words: "Language translation capability for a successfully running ASP.NET application". But this application was never designed with the intention for supporting language translation. It didn't have any concept of localization/resource files and other things. The ground work was started by building a concept that needed me to change the basic structure and include the concept of localization, resource files, and all the related stuff, which in turn meant a lot of effort and business hours, but jQuery-Translator changed all of this: it just took me 12 hours to understand and have it implemented within the ASP.NET application.

Using the Code

This article will be helpful to all those who wish to have a language translator integrated into their existing applications/websites. This will now be minutes' work. Please find all the libraries and scritps required in the source files attached along with the article. Now you need to just include a reference to one of the scripts in your application's page and you can start using the language translator inside your page.

<script src="Scripts/TranslatorScript.js" type="text/javascript"></script>

The code is simple and easy to understand, much of it can be understood by just going through it. "TranslatorScript.js" holds the key to the implementation. The initial section loads all the required script files.

LoadScript(scriptPath + "jQuery-BlockUI.js");
LoadScript(scriptPath + "jquery.translate-1.4.7.min.js");
LoadScript(scriptPath + "jquery.cookie.js");

Here, LoadScript is the function which finds the location of the script files and loads them.

function getScriptsPath() {
    var scripts = document.getElementsByTagName("script");
    var regex = /(.*\/)TranslatorScript/i;
    for (var i = 0; i < scripts.length; i++) {
        var currentScriptSrc = scripts[i].src;
        if (currentScriptSrc.match(regex))
            return currentScriptSrc.match(regex)[1];
    }
    return null;
}

The loadTranslator() function is the center of the article which does all the magic. This is the function which handles the language translation during DOM structuring. This function holds the UI code which is added to the page which provides a UI interface for language selection.

function loadTranslator() {

    $.translate(function() {

        try {
            $('#translate-bar').html("");
        }
        catch (e) {
        }

        var selectedLanguage = $.cookie('selectedLanguage');
        //get previously translated language

        if (selectedLanguage) {
            if(selectedLanguage != 'en')
                translateTo(selectedLanguage);
        }

        function translateTo(selectedLanguage) {
            $('body').translate('english', selectedLanguage, {
                not: '.jq-translate-ui',
                fromOriginal: true,
                start: function() {
                    $('#jq-translate-ui').val(selectedLanguage);
                    $.blockUI.defaults.applyPlatformOpacityRules = false;
                    $.blockUI(
                            {
                                message: 'Language Translation In Progress, Please Wait...',
                                css:
                                {
                                    border: 'none',
                                    padding: '10px',
                                    backgroundColor: '#000',
                                    '-webkit-border-radius': '9px',
                                    '-moz-border-radius': '9px',
                                    opacity: .9,
                                    color: '#fff'
                                },
                                overlayCSS: { backgroundColor: '#000', opacity: 0.6, 
                                  '-moz-opacity': '0.6', width: '100%', height: '100%' }
                            });
                },
                complete: function() { $.unblockUI({ css: { cursor: 'default'} }); }
            });
        }
    // Languages are loaded into the selection box    
        $.translate.ui({
            tags: ["select", "option"],
            //a function that filters the languages:
            //this can be an array of languages/language codes too
            filter: $.translate.isTranslatable,
            //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
            }).change(function() {
            $.cookie('selectedLanguage', $(this).val(), { path: '/' });
            translateTo($(this).val());
            return true;
        }).appendTo('#translate-bar');
    }); 
}

The source files include scripts and other related files along with images which will help in building a layer above the existing page content, and provides the suitable UI required for the language translation. This is a very simple and basic implementation. The script files work on the DOM structure of the page content. When a page is loaded and once the DOM structure of the page is ready, the content is translated into the required language by the jQuery Translator. For more information on jQuery-Translator, please visit http://code.google.com/p/jquery-translate/.

Points of Interest

This article will be helpful to all those who wish to integrate a language translator in their site/application with minimal effort and implementation time.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Govardhana Reddy
Web Developer India
India India
This is Govardhana Reddy, i am here to explore this world of INTERNET. I feel this is one way through which i can explore this world of INTERNET.
 
I want to be one among the best in this profession (a Software Developer, not a Software Engineer its a bit Controversial.) if not the "BEST"
 
My definition of a Software Engineer : "A person who knows what to cut/copy and where to paste".
 
Apart from my technical stuff I love Long Drives, Computer Gaming, Sports, Bikes and much more to say.
 
Anyways long road ahead keep me accompanied...
Follow on   Twitter

Comments and Discussions

 
Questionjquery language translator Pinmemberelamoorthy11-Sep-12 19:07 
QuestionLatest Version with Google API v2 PinmemberGovardhana Reddy25-Dec-11 6:29 
Hi,
 
Please find the updated version of the implementation which makes use of Google Translator API v2 here. Google Translator API v2 Implementation[^]
Regards,
Govardhana Reddy R
apondu@gmail.com
apondu@neversaydie.co.in
http://www.apondu.50megs.com

QuestionMy vote of 5 -> Pinmemberkasunt1-Nov-11 7:32 
Generaldepricated? Pinmemberguylwalker31-Oct-11 12:57 
GeneralRe: depricated? PinmemberDaniel Lo Nigro1-Nov-11 12:31 
GeneralRe: depricated? PinmemberGovardhana Reddy28-Dec-11 6:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140709.1 | Last Updated 30 Oct 2011
Article Copyright 2011 by Govardhana Reddy
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid