0

I am trying to implement a very simple MUI with jQuery. Tried a few plugins but all of them are changing a language inside tags with specific ID, class name or data attribute. I need to translate an interface by shortcodes like {%translateme%}.

The HTML code I am using is:

<div>{%projects%}</div>
<input type="text" placeholder="{%tasks%}"/>
<div><a href="#" id="en">English</a> | <a href="#" id="fr">French</a></div>

And my jQuery is:

var english = {
  "projects": "Projects",
  "tasks": "Tasks",
};

var french = {
    "projects": "Projets",
  "tasks": "Tâches",
};

$(document).ready(function() {
    $("#en").click(function(){
            console.log('changeLanguage English');
        //changeLanguage function
    });
});
$(document).ready(function() {
    $("#fr").click(function(){
            console.log('changeLanguage French');
        //changeLanguage function
    });
});

By default I need to load English if possible.

Please find the example on jsFiddle here: https://jsfiddle.net/g1hpkphg/2/

Many thanks for your help in advance.

1 Answer 1

1

You have to understand that "shortcodes" are just plain text nodes into DOM, not some pieces of texts that can be substituted like it is normally done into templating engines.

Because of this difference you need to define a way to find these translatable pieces into DOM, and for DOM the smallest piece is a node. Hence using some nodes (html tags are the simplest to find) to define translatable pieces of texts will help you to solve your task. For example you can try to use e.g. span with data- attributes like: <span data-locale="projects">Projects</span> and then you will be able to do something like:

$('[data-locale]').each(function(){
  var $this = $(this);
  $this.text(locales[locale][$this.data('locale')]);
})

In my example locales is an object with locale identifiers as a key and localized strings as values. locale is identifier of current locale. It will be simpler to operate compared to accessing different variables for different locales.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.