JavaScript translate

17.Feb.2011

When making a multilingual application programmers usually find themselves in a bit of a problem when having need to translate things in JavaScript as those JavaScript files are usually separated from PHP so they can’t call translate function for this purpose. To solve this problem I have created JavaScript translate class, so please check following snippet to find how to define JavaScript translate class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var javaScriptTranslate = function() {
    var translations = {};
 
    return {
        translate: function(text) {
            if(typeof translations[text] === 'undefined') {
                return text;
            } else {
                return translations[text];
            }
        },
        init: function(translationArray) {
            translations = translationArray;
        }
    };
}();

After you have defined your JavaScript translate class you need to load list of translations (usually saved as PHP array, and if not – convert it to PHP array):

1
javaScriptTranslate.init(<?php echo json_encode($translation); ?>);

Now – all you have to do is call function translate from javaScriptTranslate class and you’ll find it really easy. See for yourself in following snippet:

1
alert(javaScriptTranslate.translate('Hello dear friend - I am JavaScript translate class'));

Notice: Your PHP value of variable $translation should be an associative array where key is value you are translating and value is translation of desired value. Example for German translation in this snippet would be following:

1
2
3
4
$translation = array(
   'Hello dear friend - I am JavaScript translate class' =>
      'Hallo lieber Freund - ich bin JavaScript Übersetzen Klasse'
);