[MultiLang] MultiLang.js (ok)
https://github.com/BdR76/MultiLanguage
Previous========== Start [MultiLang] ===========Next[MultiLang] Localizing JavaScript apps with jQuery.i18n (ok) (full)
Last updated
https://github.com/BdR76/MultiLanguage
Last updated
C:\xampp\htdocs\windows\index.html
<!doctype html>
<html>
<head>
<title>JavaScript multi-language localisation example</title>
<link rel="stylesheet" href="style.css" />
</head>
<script type="text/javascript" src="multilang.js"></script>
<script type="text/javascript">
var multilang;
function onLoad() {
// create object, load JSON file, default to 'nl', and callback to initList when ready loading
multilang = new MultiLang('languages.json', 'nl', this.initList);
// alternatively
//multilang = new MultiLang('languages.json', null, this.initList); // default to browser language
//multilang = new MultiLang('languages.json'); // only load JSON, no callback
}
function langSelectChange(sel) {
// switch to selected language code
multilang.setLanguage(sel.value);
// refresh labels
refreshLabels();
}
function initList() {
// get language list element
var list = document.getElementsByName("listlanguages")[0];
// clear all options
list.options.length = 0;
// add all available languages
for (var key in multilang.phrases) {
// create new language option
var lang = document.createElement("option");
lang.value = key;
lang.innerHTML = multilang.phrases[key]['langdesc'];
// append to select element
list.appendChild(lang);
}
refreshLabels();
}
function refreshLabels() {
// Basically do the following for all document elements:
//document.getElementById("Options").textContent = multilang.get("Options");
// loop through all document elements
var allnodes = document.body.getElementsByTagName("*");
for (var i = 0, max = allnodes.length; i < max; i++) {
// get id current elements
var idname = allnodes[i].id;
// if id exists, set get id current elements
if (idname != '') {
allnodes[i].textContent = multilang.get(idname);
};
};
}
</script>
<body onload="onLoad()">
Select language from list to switch between translations:
<select name="listlanguages" onchange="langSelectChange(this)">
</select><br />
<div>
<div id="Start" class="bl">Start game</div>
<div id="Sound" class="bl">Sound</div>
<div id="Editor" class="bl">Editor</div>
<div id="Music" class="bl">Music</div>
<div id="Options" class="bl">Options</div>
</div><br>
<div>
<a id="Reset game">Reset game</a><br />
<div id="No" class="rd">no</div>
<div id="Yes" class="gr">yes</div>
</div><br>
<div>
<a id="Credits1">Credits1</a>
Harry<br />
<a id="Credits2">Credits2</a>
Dick<br />
<a id="Credits3">Credits3</a>
Tom<br />
</div><br>
<div id="EndText">End text</div>
</body>
</html>
C:\xampp\htdocs\windows\multilang.js
// MultiLang - BdR 2016
// JavaScript object to handle multilanguage, load phrases from JSON etc.
var MultiLang = function(url, lang, onload) {
// variables
this.phrases = {};
// keep only first two chareacters, for example 'en-US', 'fr', 'nl-NL', 'it', 'zh' etc.
this.selectedLanguage = (lang || navigator.language || navigator.userLanguage).substring(0, 2);;
// onLoad callback function, call after loading JSON
this.onLoad = onload;
// load json from url
if (typeof url !== 'undefined') {
var obj = this;
var req = new XMLHttpRequest();
// NOTE: will load asynchronously!
req.open("GET", url, true);
//req.setRequestHeader("User-Agent", navigator.userAgent);
req.onreadystatechange = function(evt) {
if (evt.target.readyState == 4 && evt.target.status == 200) // status == 200, do not allow "Cross origin requests"
//if (evt.target.readyState == 4)// TESTING allow "Cross origin requests" to load from local harddisk
{
// load translations
this.phrases = JSON.parse(evt.target.responseText);
// verify that the currently selected language exists in the translations
this.setLanguage(this.selectedLanguage);
// do callback when loading JSON is ready
if (this.onLoad) {
this.onLoad();
}
};
}.bind(obj); // NOTE: bind onreadyfunction to MultiLang instead of XMLHttpRequest, so MultiLang.phrases will be set instead of added to XMLHttpRequest
req.addEventListener("error", function(e) {
console.log('MultiLang.js: Error reading json file.');
}, false);
req.send(null);
};
this.setLanguage = function(langcode) {
// check if language code exists in translations
if (!this.phrases.hasOwnProperty(langcode)) {
// if it doesn't exist; default to first language
// NOTE: the order of properties in a JSON object are not *guaranteed* to be the same as loading time,
// however in practice all browsers do return them in order
for (var key in this.phrases) {
if (this.phrases.hasOwnProperty(key)) {
langcode = key;
break;
};
};
};
// set as selected language code
this.selectedLanguage = langcode;
};
this.get = function(key) {
// get key phrase
var str;
// check if any languages were loaded
if (this.phrases[this.selectedLanguage]) str = this.phrases[this.selectedLanguage][key];
// if key does not exist, return the literal key
str = (str || key);
return str;
};
}
C:\xampp\htdocs\windows\languages.json
{
"en":
{
"langdesc": "English",
"Start": "Start game",
"Editor": "Editor",
"Options": "Options",
"Sound": "Sound",
"Music": "Music",
"Reset game": "This will reset your game progress. Are you sure?",
"Yes": "Yes",
"No": "No",
"Credits1": "Program by",
"Credits2": "Artwork and graphics by",
"Credits3": "Special thanks to",
"EndText": "Congratulations! Thank you for playing!"
},
"vi":
{
"langdesc": "Vi",
"Start": "Bắt đầu trò chơi",
"Editor": "Người chỉnh sửa",
"Options": "Tùy chọn",
"Sound": "Âm thanh",
"Music": "Nhạc",
"Reset game": "Điều này sẽ đặt lại tiến trình trò chơi của bạn. Bạn có chắc không?",
"Yes": "Có",
"No": "Không",
"Credits1": "Chương trình của",
"Credits2": "Tác phẩm nghệ thuật và đồ họa của",
"Credits3": "Trân trọng cảm ơn",
"EndText": "Xin chúc mừng! Cảm ơn vì đã chơi"
},
"de":
{
"langdesc": "German",
"Start": "Spiel starten",
"Editor": "Editor",
"Options": "Optionen",
"Sound": "Geräusche",
"Music": "Musik",
"Reset game": "Möchten Sie Ihren Fortschritt wirklich zurücksetzen?",
"Yes": "Ja",
"No": "Nein",
"Credits1": "Programm von",
"Credits2": "Artwork und Grafiken von",
"Credits3": "Mit Dank an",
"EndText": "Gratuliere! Danke für's Spielen!"
},
"fr":
{
"langdesc": "French",
"Start": "Jouer",
"Editor": "Éditer",
"Options": "Paramètres",
"Sound": "Sons",
"Music": "Musique",
"Reset game": "Voulez-vous vraiment réinitialiser votre progression?",
"Yes": "Oui",
"No": "Non",
"Credits1": "Programme de",
"Credits2": "Illustrations et graphiques de",
"Credits3": "Remerciements à",
"EndText": "Félicitations! Merci d'avoir joué le game!"
},
"es":
{
"langdesc": "Spanish",
"Start": "Comenzar",
"Editor": "Editor",
"Options": "Opciones",
"Sound": "Sonido",
"Music": "Música",
"Reset game": "Reiniciar todos los puzzles resueltos. ¿Estás seguro?",
"Yes": "Sí",
"No": "No",
"Credits1": "Programa por",
"Credits2": "Ilustraciones y gráficos por",
"Credits3": "Con agradecimiento",
"EndText": "¡Felicidades! ¡Gracias por jugar!"
},
"nl":
{
"langdesc": "Dutch",
"Start": "Start spel",
"Editor": "Bewerken",
"Options": "Opties",
"Sound": "Geluid",
"Music": "Muziek",
"Reset game": "Hiermee wis je alle spelvoortgang. Weet je het zeker?",
"Yes": "Ja",
"No": "Nee",
"Credits1": "Programma door",
"Credits2": "Tekeningen en illustraties door",
"Credits3": "Met dank aan",
"EndText": "Gefeliciteerd! Bedankt voor het spelen!"
},
"ru":
{
"langdesc": "Russian",
"Start": "Начать игру",
"Editor": "Редактор",
"Options": "Опции",
"Sound": "звук",
"Music": "Музыка",
"Reset game": "Это приведет к сбросу ваш прогресс. Ты уверен?",
"Yes": "да",
"No": "Нет",
"Credits1": "Запрограммированный",
"Credits2": "Иллюстрации",
"Credits3": "Особая благодарность",
"EndText": "Поздравления! Спасибо за игру!"
}
}