-
Notifications
You must be signed in to change notification settings - Fork 1
/
translate.js
46 lines (44 loc) · 1.27 KB
/
translate.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
langdata = null;
contentLoaded = false;
document.addEventListener('DOMContentLoaded', () => {
contentLoaded = true;
translate();
});
langpos = 0;
switchLanguage = () => {
langcodes = ['en', 'de'];
langpos += 1;
if (langpos == langcodes.length) langpos = 0;
changeLanguage(langcodes[langpos]);
};
changeLanguage = (lang) => {
localStorage.setItem('lang', lang);
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
langdata = JSON.parse(xhr.responseText);
translate();
}
};
xhr.open('GET', `assets/lang/${lang}.json`, true);
xhr.send();
};
changeLanguage(
params.lang
? params.lang
: localStorage.getItem('lang')
? localStorage.getItem('lang')
: 'en'
);
translate = () => {
if (langdata == null || !contentLoaded) return;
for (elem of document.querySelectorAll('[data-translation-id]')) {
const translation = langdata[elem.getAttribute('data-translation-id')];
if (translation) elem.innerHTML = translation;
}
for (elem of document.querySelectorAll('[data-translation-placeholder-id]')) {
const translation =
langdata[elem.getAttribute('data-translation-placeholder-id')];
if (translation) elem.setAttribute('placeholder', translation);
}
};