Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery language switcher

Tags:

jquery

I want to build a website having its content in two languages. I want to use jQuery for the language switching. My idea is this:

instead of having actual content in the HTML page:

<div>Hello there</div>

I want to use classes:

HTML:

<div class="hello_EN"></div>

JS(I'm not good at JS; i've combined it with some PHP so I can make myself understood):

var EN = new array('hello_EN' => 'Hello there');
foreach($EN as $class => $content)
$(".$class").text("$content"); //this should populate all my HTML classes with its content

Then, I must have my second language array:

var RO = new array('hello_RO' => 'Salut');

Now, the switching:

$("#change_to_RO").click(function() {
       $(EN).replaceWith(RO);
});

How should I approach this? Thanks.

like image 703
Schutzstaffel Avatar asked Nov 17 '12 04:11

Schutzstaffel


1 Answers

It's probably best to not approach this from JavaScript. That being said, as an academic and learning exercise, here is just a crude idea of how you could go about something like this:

<select id="lang">
    <option>English</option>
    <option>Portuguese</option>
    <option>Russian</option>
</select>
<span data-translate="_hello">Hello</span>, 
<span data-translate="_january">January</span>!​
// Some variables for later
var dictionary, set_lang;

// Object literal behaving as multi-dictionary
dictionary = {
    "english": {
        "_hello": "Hello",
        "_january": "January"
    },
    "portuguese": {
        "_hello": "Oie",
        "_january": "Janeiro"
    },
    "russian": {
        "_hello": "привет",
        "_january": "январь"
    }
};

$(function () {

    // Lets be professional, shall we?
    "use strict";

    // Function for swapping dictionaries
    set_lang = function (dictionary) {
        $("[data-translate]").text(function () {
            var key = $(this).data("translate");
            if (dictionary.hasOwnProperty(key)) {
                return dictionary[key];
            }
        });
    };

    // Swap languages when menu changes
    $("#lang").on("change", function () {
        var language = $(this).val().toLowerCase();
        if (dictionary.hasOwnProperty(language)) {
            set_lang(dictionary[language]);
        }
    });

    // Set initial language to English
    set_lang(dictionary.english);

});​

Fiddle: http://jsfiddle.net/MBRG4/5/

like image 136
Sampson Avatar answered Oct 29 '22 23:10

Sampson