-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
47 lines (36 loc) · 1.28 KB
/
index.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
47
class KoalaTranslate {
constructor(translations = {}, currentLanguage = 'en') {
this.translations = translations;
this.currentLanguage = currentLanguage;
this.elements = document.querySelectorAll('[translate]');
this.translate();
}
translate(lang) {
if (lang) this.currentLanguage = lang;
this.elements.forEach((el) => {
el.innerHTML = this.translateToken(this.translations, el.attributes.translate.value) || '';
});
}
translateToken(source, tokenName) {
if (!(source && tokenName)) return;
const tokenArray = tokenName.split('.');
const currentSource = source[tokenArray[0]];
if (currentSource) {
return (tokenArray.length <= 1)
? currentSource[this.currentLanguage]
: this.translateToken(currentSource, tokenArray.slice(1).join('.'));
} else return '';
}
}
window.addEventListener('load', () => {
const translate = new KoalaTranslate(window.translations, 'uk');
document.querySelectorAll('[translate-lang]').forEach(el => {
el.addEventListener('click', (e) => {
translate.translate(e.target.attributes['translate-lang'].value);
document.querySelectorAll('.lang__item.active').forEach(lang =>
lang.classList.remove('active')
);
el.classList.add('active');
});
});
});