-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslation-data-attributes.js
53 lines (49 loc) · 1.32 KB
/
translation-data-attributes.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
48
49
50
51
52
53
/**
* Translator class
*
* @class Translator
* @param {Object} translateMap - A map of translation keys to their corresponding values
*/
class Translator {
/**
* Constructor
*
* @param {Object} translateMap - A map of translation keys to their corresponding values
*/
constructor(translateMap) {
/**
* The translation map
* @type {Object}
*/
this.translateMap = translateMap || {};
}
/**
* Translate all elements with a `data-translate` attribute
*
* @example
* const translator = new Translator({
* hello: 'Привіт',
* goodbye: 'До побачення'
* });
* translator.translate();
*/
translate() {
document.querySelectorAll('[data-translate]').forEach(element => {
const key = element.dataset.translate;
const translation = this.translateMap[key];
if (translation) {
element.innerHTML = translation;
} else {
console.warn(`Translation not found for key: ${key}`);
}
});
}
}
// Example Usage:
const translations = {
hello: 'Привіт',
goodbye: 'До побачення'
// other translations...
};
const translator = new Translator(translations);
translator.translate();