Reputation: 109
I'm a single software developer and I need to create various language versions within the same single web page.
When I have a HTML element like this:
<button id="btn1" >My Button</button>
What is the simplest way to change its text automatically (Javascript or JQ?) when language is set to "fr" instead of "en"?
The text shall then become "Mon Bouton" and if later on I want to add a German translation, I need to keep it simple.
I presume I could use a set of dictionnaries, one for each language? Then execute a js or jq function at load time... Or each time the user changes the current language option.
The "en" dictionnary would then look like this:
{"addButton" : "Add"}
{"DeleteButton" : "Delete"}
And so on...
But how will I proceed to the change?
Upvotes: 2
Views: 3292
Reputation:
It is interesting,
I never tried it,
but I did this:
html:
EN<input type="radio" name="group" id="en" checked />
FR<input type="radio" name="group" id="fr" />
<hr />
<div class="content">
<button data-en="My Button" data-fr="Mon Bouton"></button>
<div data-en="something" data-fr="quelque chose"></div>
</div>
js:
$(":radio").on("click", function(){
/* I used two radios: #en, #fr (check in html code) */
var lang = this.id;
/* lang will take the id of the clicked radio ("en" or "fr") */
$(".content *").each(function(){
$(this).html( $(this).data(lang) );
/* then set the $.html() with the $.data() - functions of jquery */
});
});
$("#en").trigger("click");
/* starts with english language */
Check out the functions of jquery:
Upvotes: 1
Reputation: 91
You can define (or generate it from server) translations like this:
translations = {
'en': {
'button_text': 'My Button'
},
'fr': {
'button_text': 'Mon Bouton'
}
};
And for example you have some buttons that changes language:
<button data-language="en">English</button>
<button data-language="fr">French</button>
So you can bind click event and it will change language like this:
$('button[data-language]').click(function(e) {
var lang = $(this).attr('data-language');
$('button#btn1').text(translations[lang]['button_text']);
});
If you want to add additional language, you just need to add translations and button and you dont need to change js code
Upvotes: 2