How to dynamically change language using jquery-i18n-properties and JavaScript?

24,229

Yeah it's easy. In fact, there's example that does just that on jQuery.i18n.properties site (http://codingwithcoffee.com/files/trunk/index.html).

Trick is, to simply reinitialize plugin with new language. Abstract your current code into another function, that accepts lang as parameter. Initialize with some default language, and once user changes the current language, pass it to that function.

function changeLang(lang) {
    jQuery.i18n.properties({
        name: 'Messages', 
        path: 'bundle/', 
        mode: 'both',
        language: lang, 
        callback: function() {
            $("#msg_welcome").text(jQuery.i18n.prop('msg_welcome'));
            ...
        }
    });
}

// somewhere else in your code
// change to english
changeLang('en_EN');
// change to other
changeLang('pt_PT');
Share:
24,229
Barbara PM
Author by

Barbara PM

Updated on March 27, 2020

Comments

  • Barbara PM
    Barbara PM about 4 years

    I'm providing i18n to my website using jquery-i18n-properties plugin. I have already changed my HTML and do the following in order to load the .properties that is required:

    jQuery.i18n.properties({
        name: 'Messages', 
        path: 'bundle/', 
        mode: 'both',
        language: lang, 
        callback: function() {
            $("#msg_welcome").text(jQuery.i18n.prop('msg_welcome'));
            ...
        }
    });
    

    Everything works fine. What I want to do now is allow the user to change the language pressing a button. Is there a way to do it using only javascript or this plugin without reloading the page? Thanks.