-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlang.js
More file actions
67 lines (60 loc) · 2.01 KB
/
lang.js
File metadata and controls
67 lines (60 loc) · 2.01 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
function loadLanguageFile(lang, callback) {
fetch(`translations/${lang}.json`)
.then(response => {
if (!response.ok) throw new Error("Language file not found");
return response.json();
})
.then(data => {
applyTranslations(data);
if (callback) callback();
})
.catch(error => {
console.error("Error loading translation file:", error);
});
}
function applyTranslations(translations) {
document.querySelectorAll("[data-i18n]").forEach(el => {
const key = el.getAttribute("data-i18n");
if (translations[key]) {
el.innerHTML = translations[key];
}
});
}
document.addEventListener("DOMContentLoaded", () => {
const savedLang = localStorage.getItem('preferredLanguage') || 'fr';
const langInput = document.getElementById('language');
if (langInput) {
langInput.value = savedLang;
}
loadLanguageFile(savedLang);
// Update dropdown text
const langButton = document.getElementById('selected-lang');
const selectedLi = document.querySelector(`#lang-list li[data-value="${savedLang}"]`);
if (langButton && selectedLi) {
langButton.textContent = selectedLi.textContent;
}
const langList = document.getElementById('lang-list');
if (langList) {
langList.onclick = (e) => {
if (e.target.tagName === 'LI') {
const selectedLang = e.target.dataset.value;
if (langInput) langInput.value = selectedLang;
if (langButton) langButton.textContent = e.target.textContent;
localStorage.setItem('preferredLanguage', selectedLang);
loadLanguageFile(selectedLang);
}
};
}
// Toggle dropdown
const dropdownBtn = document.getElementById('selected-lang');
if (dropdownBtn && langList) {
dropdownBtn.onclick = () => {
langList.style.display = langList.style.display === 'block' ? 'none' : 'block';
};
document.addEventListener('click', (e) => {
if (!dropdownBtn.contains(e.target) && !langList.contains(e.target)) {
langList.style.display = 'none';
}
});
}
});