How to Translate your Site in Runtime using jQuery

How to Translate your Site in Runtime using jQuery

21 77245

How to Translate your Site in Runtime using Jquery

This is very interesting question. I have read several articles for this question, and most articles tell about ways where we need refresh page to apply another localization. Yes, this is possible of course, but not too user friendly. Just imagine that your website will able to switch language like desctop applications, great, isn`t it? So, that this still possible using ordinary javascript. I will using jQuery to better comfort.

Here are samples and downloadable package:

Live Demo

Ok, download the source files and lets start coding !


Step 1. XHTML

Here are our main HTML file:

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml2/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>How to Translate your Site in Runtime using Jquery - demo</title>
<link rel="stylesheet" href="css/main.css" type="text/css" />
<script src="js/jquery.min.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="example">
<h3><a href="#">How to Translate your Site in Runtime using Jquery - demo</a></h3>
<div id="content">
<div class="lang_switcher">
<button id="en" class="lang">EN</button>
<button id="ru" class="lang">RU</button>
</div>
<div style="clear:both;"></div>
<!-- nav menu start -->
<ul id="nav">
<li><a href="#nogo" key="home" class="tr">Home</a></li>
<li><a href="#nogo" key="peoples" class="tr">Peoples >></a>
<ul>
<li><a href="#nogo" key="all_list" class="tr">All list</a></li>
<li><a href="#nogo" key="online" class="tr">Online</a></li>
</ul>
</li>
<li><a href="#nogo" key="articles" class="tr">Articles >></a>
<ul>
<li><a href="#nogo" key="js" class="tr">JavaScript</a></li>
<li><a href="#nogo" key="php" class="tr">PHP</a></li>
<li><a href="#nogo" key="html" class="tr">HTML</a></li>
<li><a href="#nogo" key="css" class="tr">CSS</a></li>
</ul>
</li>
<li><a href="#nogo" key="contact_us" class="tr">Contact us</a></li>
</ul>
<!-- nav menu end -->
<div style="clear:both;"></div>
<h2 key="welcome" class="tr">Welcome guests</h2>
<hr />
<div>A man bribes a rabbit with wicked dentures to run away with him in a sailboat via an ambulance. Bribing Koalas to remain illegally in one place. Trees anchor me in place. / Your mom drives the ambulance, but the city is farther than it appears.</div>
</div>
</div>
</body>
</html>

As you know, for localization we should use keys and values (translated strings to different languages). As you noticed, I just store key name inside required element, plus mark, that this element translatable. Here are sample: <h2 key="welcome" class="tr"> – mean that I using key ‘welcome’ for following translation.

Step 2. CSS

Here are used CSS file.

css/main.css

body{background:#eee;font-family:Verdana, Helvetica, Arial, sans-serif;margin:0;padding:0}
.example{background:#FFF;width:500px;height:500px;font-size:80%;border:1px #000 solid;margin:0.5em 10% 0.5em;padding:1em 2em 2em;-moz-border-radius:3px;-webkit-border-radius:3px}
.lang_switcher{float:right;overflow:hidden;}
/* nav menu styles */
#nav,#nav ul{list-style:none;font:10px verdana, sans-serif;border:1px solid #000;background:#fff;position:relative;z-index:200;border-color:#eca #b97 #a86 #edb;border-width:1px 2px 2px 1px;margin:0;padding:0 0 5px}
#nav{height:25px;padding:0}
#nav table{border-collapse:collapse}
#nav li{float:left;padding:0 20px 0 10px}
#nav li li{float:none}
#nav li a li{float:left}
#nav li a{display:block;float:left;color:#888;height:25px;padding-right:5px;line-height:25px;text-decoration:none;white-space:nowrap}
#nav li li a{height:20px;line-height:20px;float:none}
#nav li:hover{position:relative;z-index:300;background:#fff}
#nav a:hover{position:relative;z-index:300;text-decoration:underline;color:#b75}
#nav :hover ul{left:0;top:22px}
#nav a:hover ul{left:-10px}
#nav li:hover li:hover > ul{left:-15px;margin-left:100%;top:-1px}
#nav li:hover > ul ul{position:absolute;left:-9999px;top:-9999px;width:auto}
#nav li:hover > a{text-decoration:underline;color:#b75}
#nav a:hover a:hover ul,#nav a:hover a:hover a:hover ul,#nav a:hover a:hover a:hover a:hover ul,#nav a:hover a:hover a:hover a:hover a:hover ul{left:100%;top:-1px}
#nav ul,#nav a:hover ul ul,#nav a:hover a:hover ul ul,#nav a:hover a:hover a:hover ul ul,#nav a:hover a:hover a:hover a:hover ul ul{position:absolute;left:-9999px;top:-9999px}

Step 3. JS

Here are used JS files.

js/jquery.min.js and js/main.js

First file – just jQuery library (available in package), source of second file here:

// preparing language file
var aLangKeys=new Array();
aLangKeys['en']=new Array();
aLangKeys['ru']=new Array();
aLangKeys['en']['home']='Home';
aLangKeys['en']['peoples']='Peoples >>';
aLangKeys['en']['all_list']='All list';
aLangKeys['en']['online']='Online';
aLangKeys['en']['articles']='Articles >>';
aLangKeys['en']['js']='JavaScript';
aLangKeys['en']['php']='PHP';
aLangKeys['en']['html']='HTML';
aLangKeys['en']['css']='CSS';
aLangKeys['en']['contact_us']='Contact us';
aLangKeys['en']['welcome']='Welcome guests';
aLangKeys['ru']['home']='Главная';
aLangKeys['ru']['peoples']='Пользователи >>';
aLangKeys['ru']['all_list']='Весь список';
aLangKeys['ru']['online']='В сети';
aLangKeys['ru']['articles']='Статьи >>';
aLangKeys['ru']['js']='Яваскрипт';
aLangKeys['ru']['php']='ПХП';
aLangKeys['ru']['html']='ХТМЛ';
aLangKeys['ru']['css']='КСС';
aLangKeys['ru']['contact_us']='Напишите нам';
aLangKeys['ru']['welcome']='Добро пожаловать';
$(document).ready(function() {
// onclick behavior
$('.lang').click( function() {
var lang = $(this).attr('id'); // obtain language id
// translate all translatable elements
$('.tr').each(function(i){
$(this).text(aLangKeys[lang][ $(this).attr('key') ]);
});
} );
});

Here are most interesting part. Firstly I allocate my language array with keys and values. Currently it contain only 2 languages. But if you know more languages – you will easy to make more translations. So what I doing when I click button to switch language – running through all elements which marked as translatable (‘tr’ class), and apply custom value from our lang keys array depends on selected switcher value.


Live Demo

Conclusion

I hope that today’s article was very interesting and not so difficult. Sure it will useful for your projects. Do not forget to say thank you :) Good luck!

SIMILAR ARTICLES

Bootstrap Forms

0 60
jQuery Mobile Lesson 6

0 15

21 COMMENTS

  1. This approach is “okay”, but suffers a couple of issues:

    1. you download data for every language to every user, but you probably really only need to download the language the user understands (An AJAX approach could resolve this)

    2. third-party translation services may not know how to help you

    For enterprise-scale applications, these issues would probably be show-stoppers, but for many applications, the approach you propose is “the simplest thing that would work”; you can build from there as necessary…

    Most language translations are done on the server-side, using resource bundles.
    The Locale header tells the server what language the user prefers.
    It is normally not necessary to switch the language on-the-fly and if it is, users generally expect a page refresh or even a redirect, so…

    • Thanks for good answer,
      1. Using gzip to pack JS files will greatly reduce its size. So maybe this approach is not so bad? :)
      2. Why? .. you always will have EN translation by default, so even google translator will able to translate this page too.

      so commonly, this is possible to use this to translate websites. Possible I`ll realize this in one of my websites. Currently, this is as one of nice ideas.

    • Yes, possible, but this plugin doing a little another.
      About adding custom params (like key) into different Tags not should violate html syntax. You can use your own key if you wish.

  2. jquery.translate is a wrapper over the Google language and translation API. Therefore we must first check if Google does provide support for these languages.

  3. I think Its better to use Google translator API Using Jquery
    by that way you don’t need to add translated keyword for each word and its also easy to use

    thanks

    • Hi Abhilash,
      This is already dynamic text translation. If you need to translate something else – just add more language keys and use them.

  4. Hi I was looking to implement this code in my project.The thing is it works on your site.When I downloaded the package and tested in my localhost it does not display the non-English characters properly. I have the encoding set to utf-8, but it does not help.Any ideas what’s wrong?

  5. Great idea! Good work!

    Why do you not use “data-key” attribute instead of “key”? It’s valid Html 5. :)

    We can also try to detect browser language on load.

    • Hi Vincent,
      You may use any attribute name you want (for instance: data-key).
      In this case you will need to customize our JS code on line 38

    • Hi Nidhi,
      In order to add new languages you just need to expand the aLangKeys array with new language(s) you need.

  6. you have given an array of elements for language translation (like for home it is Главная)but i need code for entire web page irrespective of content it should change accordingly where we can’t store element for each word

  7. Hi,
    After adaptation to my project, this method works fine for me.
    However, I have a problem with input type=”button” jQuery ui version.
    Any idea?
    Thanks a lot

Leave a Reply