jQuery Multi-Language Plugin

Last Updated on January 27th, 2012 (sub-pages have their own dates)

Instantly switch content languages client-side

You can get the latest open-source from GitHub here: https://github.com/coolbloke1324/jquery-lang-js

Change language without reloading the page or doing a request to the server. See the example!!

This jQuery plugin allows you to create multiple language versions of your content by supplying phrase translations from a default language such as English to other languages.

Showcase

Here are some third-party sites using our plugin:

http://www.kava.es

http://www.kava.es

Example

On the example page there are three language packs, English,  Thai and a made-up language called “Moo”.

http://www.isogenicengine.com/jquery-lang-js/

How to use

Include the plugin script in your head tag and include any language pack you have created ensuring that you specify the charset attribute as utf-8. All language pack files should be saved as utf-8 encoded:

<script src="js/jquery-lang.js" charset="utf-8" type="text/javascript"></script>
<script src="js/langpack/th.js" charset="utf-8" type="text/javascript"></script>

When your page is loaded simply call the .run() method as so:

<script type="text/javascript">
    window.lang = new jquery_lang_js();
    $().ready(function () { window.lang.run(); });
</script>

Defining which elements to translate

In the HTML content itself you can denote an element as being available for translation by adding a “lang” attribute with the language of the content as such:

<span lang="en">Translate me</span>

Or any element with some content such as:

<select name="testSelect">
    <option lang="en" value="1">An option phrase to translate</option>
    <option lang="en" value="2">Another phrase to translate</option>
</select>

Dynamic content

If you load content dynamically the plugin will need to know when the content has been loaded in order to work correctly. After loading any content always call the plugin’s .run() method which will automatically scan the content and translate into the current language.

Switching languages

To switch languages simply call the .change() method, passing the two-letter language code to switch to. For instance here is a switcher that will change between English and Thai as used in the example page:

<a href="#lang-en" onclick="window.lang.change('en');">
    Switch to English
</a> | <a href="#lang-en" onclick="window.lang.change('th');">
    Switch to Thai
</a>

The onclick event is the only part that matters, you can apply the onclick to any element you prefer.

Define a language pack

Language packs are defined in JS files and are added to the plugin like so:

jquery_lang_js.prototype.lang.th = {
    'Property Search':'ค้นหา',
    'Location':'สถานที่ตั้ง',
    'Budget':'งบประมาณ',
    'An option phrase to translate':'งบประมาณงบประมาณสถานที่ตั้ง',
}

That example just defined a language pack to translate from the default page language English into Thai (th). Each property inside the object has a key that is the English phrase, then the value is the Thai equivalent.

It’s that simple!

License

This plugin and all code contained is Copyright 2011 Irrelon Software Limited. You are granted a license to use this code / software as you wish, free of charge and free of restrictions except one: Please tell us when you are using this plugin on your site! We will showcase it as above and link to it so that others can see the plugin in action! It would also be super-awesome if you could tweet / blog that you found the plugin useful and provide a link to it so that others can find it too. Thanks!

If you like this project, please consider Flattr-ing it! http://bit.ly/qCEbTC

This project is part of the Isogenic Game Engine, an HTML5 MMO Real-time Multiplayer 2D & Isometric Canvas & DOM Game Engine for the Modern Web. www.isogenicengine.com

  • Mail

    - how to apply the script on inputs/submits/etc?
    - any workarounds for adding multiple language files? Seems like the language selection does not work properly if there is more than one. Thanks!

    • http://www.isogenicengine.com Rob Evans

      Hi,

      The script doesn’t apply itself to inputs but it would be an easy change… instead of using the .html method, you could detect an input and then change the text with the jQuery .val method. If you fork the githib project and make the change you can do a pull request and I’ll add the update to the code! :)

      Multiple languages should work fine. Each language should be under its own two-letter ISO country code. It’s .th for Thai, .en for english etc.

      If you are having problems using multi-language switching, please give me the URL of the page you’ve used it on and I’ll have a look for you!

      • Mail

        http://la-palma.pl/lang/

        I’m not a coder, so:a) thank you for your script, it’s exactly what I was searching for, and easy to modify with minimum coding know-how;
        b) I don’t actually understand “fork the githib” sort of things? ;)

        So, in the uploaded example,you can see it switches between polish/english and polish/spanish, but won’t work for english/spanish.

        Thanks in advance ;-)

        • http://www.isogenicengine.com Rob Evans

          No worries! I’ll take a look and see what I can do!

        • http://www.isogenicengine.com Rob Evans

          Hey, I’ve updated the code on github so you need to download a new copy. I’ve fixed a bug that stopped more than two languages working and also added support for button elements so your form’s buttons will also change language. :)

          • Mail

            you’re the best ;-) Thank you

            • http://www.isogenicengine.com Rob Evans

              Hey, just following up, did that work ok for you?

              • Guest

                yap!

                http://kava.es
                Cheers!

                • http://www.isogenicengine.com Rob Evans

                  Hey that looks fantastic, do you mind if I link to it in the page to show off the capabilities?

  • Spine

    Love the script! I know that it says “Instantly switch content languages client-side”, but is there a way to fadein/fadeout the change?

    • http://www.isogenicengine.com Rob Evans

      Hey there, no it would be quite complicated to make a fade function. There would need to be two separate copies of each language-switching element, one to fade from and the other to fade to… it would probably add a lot of bloat to the plugin too unfortunately.

  • http://www.isogenicengine.com Rob Evans

    Hey there, I’m not too familiar with jQuery-mobile but I would assume that you can just do something like:

    $('.ui-btn-text').attr('lang', 'en');

    Before you start this plugin. That code will select ALL elements with the class “ui-btn-text” and add a lang=”en” attribute to them. This is ok if you only run it once at the top of your page but if you are using dynamic content, you should use the code below.

    If your popup dialog does not exist on the page but is dynamically generated, make sure that once it is on screen, call the run method of this plugin again after applying a language attribute to those elements that do not currently have one.

    open.my.dialog(); // A fake method that I'm using here to represent your open dialog code - remove this, it is not real and will cause an error

    // Now add a language attribute to any dialog button element that does not have one
    $('.ui-btn-text').each(function (index, el) {
        var elem = $(el);
        // Does the element have a lang attribute already?
        if (!elem.attr('lang')) {
            // No lang attribute exists, create one
            elem.attr('lang', 'en');
        }
    });

    // Now tell the language plugin that you have new content to scan
    window.lang.run();

    Let me know how that goes. There may be differences in the jQuery-mobile library that I am unaware of but this code *should* be ok.

    Also, if you have a project you are using this in, please drop me a link to it and I’ll add it to the page above as a showcase! :)

  • Rajeevkdave

    I am using this and this tool is very easy to implement. Thanks. I have one question . Language option is not reflecting in Button. And same I want to apply foy HTML5 placeholder text. How it is possible?

    • http://www.isogenicengine.com Rob Evans

      Hi ya,

      The script doesn’t support the button tag but I’ll see what I can do to update it to support it. It does support the input type=’button’ so you can use that if that is acceptable. Again, the same is true for the placeholder text. I’ll take a look when I get a minute and see about updating the github code.

    • http://www.isogenicengine.com Rob Evans

      I have updated the plugin to work with button elements and placeholder text values. You can get the latest version from GitHub.

  • Javier

    Hi,
    I’m testing this script and it is really fantastic, Great job !!
    Just I have an issue not able to solve :  how do I to translate the text of a javascript alert message box ?
    Thanks in advance

    • http://www.isogenicengine.com Rob Evans

      Hi Javier, I’ve updated the plugin to include a new method called convert() that will convert any phrase to the current language. You can download the latest version of the plugin to get access to the new functionality.

      To use the new convert() method in an alert() call you would do:

      alert(window.lang.convert('Some alert text'));

      • Javier

        Hi Rob,
        Not only this plugin is outstanding but you too !!  I am admired for the energy and dedication that you devote to this project.
        Javier
        Barcelone, Spain

        • http://www.isogenicengine.com Rob Evans

          :) many thanks for the kind comments. It’s a pleasure to create open-source software that can hopefully help people out. I just wish I could make the entire Isogenic Game Engine open-source too but then I wouldn’t have a company that made any money!!

  • Mike

    my  comments

  • http://www.isogenicengine.com Rob Evans

    The code has now been updated to support placeholder text, button elements and also translated text in JavaScript such as calls to the alert() method. See the latest readme on GitHub for the usage!

  • Unpyp

    Wow really nice plugin…Just trying to figure out with sIFR the way to used it. Have any idea how i could call this function each time i’m switching language :     if(typeof sIFR == “function”){
         sIFR.replaceElement(named({sSelector:”h1″, sFlashSrc:”customfont.swf”, sColor:”#000000″}));      
        };

    Because for the moment it work fine but when I change language I need to refresh to have my customfont.
    Thanks in advance
    Keep up the good work! =)

  • Mwolfndk

    I’ve caught another one. The reset-type-button.
    one addition to the three switch statements in jquery-lang.js. That’s it.
    fantastic work
    thanks

  • Chris

    I LOVE this tool, it’s simple and elegant! However, when I change pages, the language reverts to the default. Is there any way for the script to check the browser’s default language and load that unless another language is requested and then keep that language until another is requested?

    Thanks,
    Chris

    • Blablabla

      I have exactly the same issue…Is someone able to keep the language selected?

      Thanks

      • http://www.isogenicengine.com Rob Evans

        I think the best way to solve this is to enable cookies when a language is changed, that way when each page is loaded, it can be changed to the current language automatically.

        What do you think? Is the cookie solution the best way forward?

        When the plugin was written I was only considering web-app style pages that didn’t reload but instead changed their content dynamically. Obviously it is being used for other situations as well now. Let me know your thoughts on the cookie idea. If it is a good one I’ll update the code to include cookie support.

        • Chris

          I thought about cookies, but wanted something a little more “fool-proof”, particularly if cookies are disabled or if the client dumps cookies and has to select a language again.

          I know very little about scripting, which explains why the following code doesn’t quite work. I was trying to get PHP to detect the default browser language and output that as a variable. I could then use it the “lang” attribute to automatically load the requested language. The variable successfully outputs the variable into the language request attribute, but the script isn’t loading the assigned language pack.


          // PHP Broser Language Detect


          // Load Result into Variable

              var language = navigator.browserLanguage;
              if (language.indexOf('en') > -1) lang = 'en';
              else if (language.indexOf('zh') > -1) lang = 'zh';
              else if (language.indexOf('ja') > -1) lang = 'ja';
              else if (language.indexOf('ko') > -1) lang = 'ko';
              endif



          lang=""

          What do you think?

          Cheers,
          Chris

        • Chris

           Dang, the PHP and HTML didn’t output. I was hoping the CODE tags would have done the trick. Maybe just posting it naked will work?

          PHP
          $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);

          HTML
          lang=”"

        • Chris

           OK, still missing the HTML. Sorry for the blasting your comments! lol

          Basically, just use PHP to echo the $lang variable.

          • http://www.isogenicengine.com Rob Evans

            Hey, no worries… it can be a little frustrating. You could use http://pastebin.com/ to paste the code then post the link?

          • http://www.isogenicengine.com Rob Evans

            I’ll remove your extra comments and so you can post a new one if you like?

        • Chris

          New comment! Rob, if you would be so kind as to delete the previous mess, this one replaces all of it. Sorry again, and thanks for suggesting pastebin.com.

          I thought about cookies, but wanted something a little more
          “fool-proof”, particularly if cookies are disabled or if the client
          dumps cookies and has to select a language again.

          I know very
          little about scripting, which explains why the following code doesn’t
          quite work. I was trying to get PHP to detect the default browser
          language and output that as a variable. I could then use it the “lang”
          attribute to automatically load the requested language. The variable
          successfully outputs the variable into the language request attribute,
          but the script isn’t loading the assigned language pack.

          http://pastebin.com/yR6wX3tG
          What do you think?

          Cheers,
          Chris

          • http://www.isogenicengine.com Rob Evans

            I believe this might do what you’ve looking for:

            http://pastebin.com/wH5WfYLY 

            • Chris

              The site blew up. :-(

              Parse error: syntax error, unexpected $end in E:wampwwwproducers-group.comincludeshead.php on line 18

            • Chris

               I changed the closing PHP to specify it as PHP, which fixed the site. However, the outcome is the same as the previous script; the variable outputs the correct language code into the HTML lang attribute, but does not actually load the language.

            • Chris

               Here’s the Head if it helps: http://pastebin.com/mRfi1hmB

              I’ve been playing w/script order, combining, separating, etc. This is the way I’ve been able to get it to work if the browser default is English, but it does not work at all if the browser default is another language.

              • http://www.isogenicengine.com Rob Evans

                Any chance you can post a test page this is running on so I can see the HTML output and debug for you?

                • Chris

                   Sure thing. This is the development link for the site.

                  http://producersgroup.webuilders.org/

                • Chris

                   I’ve also noticed that the language switcher is no longer supporting multiple languages. I currently have 3 languages, and this site will ultimately have 6.

        • Mercury

          Hi Rob,
          Can we please have that cookie solution if you have the time to add it? This is great except for the language not persisting when navigating around a site.
          Is there any downsides to using cookies? You almost sounded a little guarded about using them, but I could be imagining things :)

    • http://www.isogenicengine.com Rob Evans

      On line 21 of your page code, the JavaScript is not ended properly. It is my fault looking at my pastebin code I did not end the method call correctly.

      I have fixed it in this one: http://pastebin.com/NehQDTKc

      (The dangers of writing code on the fly and not compiling it!)

    • http://www.isogenicengine.com Rob Evans

      PS, Let’s reply on this level because the comment space gets smaller and smaller otherwise :)

      You can also email if you would prefer? rob@irrelon.com

  • Chris

    Thanks for the assistance on this script so far!

    I got multi-language switching fixed. Turns out I left out quote mark on one of the link triggers. Doh!

    I’ve got the updated version of your script plugged in, but it’s still not working. When the browser default language is anything other than the default site language (en)1. The browser default language does not load2. Am not able to manually switch to any language

    Cheers,
    Chris
     

    • http://www.isogenicengine.com Rob Evans

      Hi Chris,

      Looks like the language is changing before the .run() has been executed. That’s probably due to the two separate script sections.

      Can you try to alter it so the outcome is like this:

      http://pastebin.com/EmBFwk7A 

      • Adriag

        Hi Chris & Rob, i’ve got the same problem (changing pages reverting lang) … i’ve tried solve it reading your comments, but i dont know much about coding :( , can you help me? maybe pasting a full code mini-example, please!
        Thanks a lot guys!
        Adri.

        • Chris

           I’ll definitely do that once we get it working.

      • Chris

         I noticed in the jquery-lang.js, it sets the default language as “en”. Should the browser default language variable be in its place somehow?

    • Chris

      I don’t understand your second comment in the script tag, “This should be output via PHP”. You have a language variable, ko, in there that is forcing one specific language. I tried this, but it’s not auto switching to the browser’s default language. Also, if the browser default language is anything other than English, the script stops working.

      http://pastebin.com/EhBaep5N

  • Rajeev Dave

    When I am creating  page Dynamically in jquery mobile ,it is not taking effect and if we have any Theam applied on it is not taking effect,

    Thanks in Advance

    For Button I have made changed in your jquery.lang.js

    You can put below line in your change function for effect.

    $(langElem).parent().find(‘.ui-btn-text’).text(newHtml);

    • http://www.isogenicengine.com Rob Evans

      I’m not familiar with jQuery Mobile so I’m not sure how to help you.

      If the page elements are being loaded / added dynamically then you should run the plugin’s .run() method after the content has been added to your page.

  • Antonio Cardenes

    Hi, I’m trying to implement your great script on a Yii framework app. I followed all instrutions but I’m not getting anywhere. Also, once I load 

        window.lang = new jquery_lang_js();
        $().ready(function () { window.lang.run(); });
       
    the webpage displays bigger, like if I zoomed in with the browser.

    Output is here: http://pastebin.com/mrNSPPTG

    Any ideas where is it failing?
    Thanks.

  • mikeman

    I’m experimenting with a jquery validation plugin found here ->

    http://bassistance.de/jquery-plugins/jquery-plugin-validation/

    and I’m trying to “switch-language” the validation messages with your plugin.
     
     they’re defined here:
     
     $(“#signupForm”).validate({
            rules: {
                firstname: “required”,
                lastname: “required”,
                email: {
                    required: true,
                    email: true
                                    ………
                                    
                            messages: {
                                    firstname: “Please enter your firstname”,
                                    lastname: “Please enter your lastname”,
                                   email: “Please enter a valid email address”,
                                   ………..
                                   
    Is it somehow possible with the convert function?

    Could you give me a hint how to do that?

    Thanks in advance!

    • http://www.isogenicengine.com Rob Evans

      Hi, you can replace the “Please enter your firstname” with:
      window.lang.convert(‘Please enter your firstname’)

    • http://www.isogenicengine.com Rob Evans

      Saying that, you will probably need to update those messages every time the language changes.

      You could do:

      window.lang.events.on(‘update’, function () {
       $(“#signupForm”).validate({        rules: {            firstname: “required”,            lastname: “required”,            email: {                required: true,                email: true                                ………                                                        messages: {                                firstname: 
      window.lang.convert(‘Please enter your firstname’) ,                                lastname: 
      window.lang.convert(‘Please enter your firstname’) ,                               email: 
      window.lang.convert(‘Please enter a valid email address’),                               ……….. 
      });

      Whilst I’m not familiar with that particular plugin, that should do it. Let me know how you get on!

  • Anonymous

    You know… the example on github is quite malfunctional.
    First of all, there’s no “Moo”-language pack on github.
    Secondly, I thought for a second that there is something wrong because the text replacement on buttons didn’t work. Only to find that when I added “Search…” to the language pack, it did indeed make the switch.So you may want to look at these two things to not maybe have some less technical people shy away from what looks like an otherwise great plugin.

  • Anonymous

    Something that is very odd… if one doesn’t style the text, in Firefox, the font switches from serif to sans-serif. And even if you enter “serif” in the CSS properties, it switches to sans-serif after swapping the text.
    While in Opera, it behaves as I would assume it should.

    • http://www.isogenicengine.com Rob Evans

      Please direct all new questions / comments to the new forum:  https://getsatisfaction.com/irrelon_software/products/irrelon_software_jquery_multi_language_plugin

  • Mercury

    My pages have images with text on them. Is it at all possible to have images change or any plans at all to add this useful feature?

    Thanks again

    • http://www.isogenicengine.com Rob Evans

      Please direct all new questions / comments to the new forum:  https://getsatisfaction.com/irrelon_software/products/irrelon_software_jquery_multi_language_plugin

  • http://www.goukaseishi.com goukaseishi

    Hi Rob, Great script.

    I want to aim my website at both English and Japanese users, but I want to make sure it detects the language the user has and shows them the Japanese or English version of the site. How do I allow this, as currently it defaults to one.

    Thanks :) .
    Keef

  • http://www.isogenicengine.com Rob Evans

    Hi everyone, the comments here are getting a bit crowded and it is difficult to follow the flow of a conversation. For that reason please direct all your queries / comments / feature requests etc to the new GetSatsifaction forum dedicated to this plugin here: 
    https://getsatisfaction.com/irrelon_software/products/irrelon_software_jquery_multi_language_plugin

  • Normis161

    I like this plugin. :) Thanks a lot.:)

  • Bornkiller

    Pleease add jquery.cookie.js function… Please please…

  • nunoq

    Hi,

    Got a question. Is there a way to change any element title to other language as well? i.e. , so when you pass the mouse hover it popups the title. Is that possible?

    Thanks,

    Nq

  • Flik185

    Hi,
    Is there any way to make the plugin work with html strings?
    If the string to translate has html code inside, everything seems to break.

    thank you

  • http://twitter.com/leifsk8er Leif Ferreira

    Hi

  • http://twitter.com/leifsk8er Leif Ferreira

     And will be good manage titles attr…