Answer the question
In order to leave comments, you need to log in
How to make a multilingual site in pure JS?
There is such an unpretentious code for the multilingual site.
html
<body>
<div class="lang df">
<a href="#en" id="lang-en">EN</a>
<a href="#ru" id="lang-ru">RU</a>
</div>
<div class="title">
<h1 class="lng-h1">Text</h1>
<button class="btn lng-btn">
Learn more
</button>
</div>
<script src="app.js"></script>
</body>
.df {
display: flex;
justify-content: space-between;
width: 60px;
}
const langArr = {
en: {
h1: 'Text',
btn: 'Learn more',
},
ru: {
h1: 'Teкст',
btn: 'Узнать больше',
},
};
const langEn = document.querySelector('#lang-en');
const langRu = document.querySelector('#lang-ru');
langEn.addEventListener('click', setLang.bind(null, 'en'));
langRu.addEventListener('click', setLang.bind(null, 'ru'));
function setLang(lang) {
if (!langArr.hasOwnProperty(lang)) return;
if (window.hasOwnProperty('localStorage'))
window.localStorage.setItem('lang', lang);
for (let key in langArr[lang]) {
let elem = document.querySelector('.lng-' + key);
if (elem) {
elem.innerHTML = langArr[lang][key];
}
}
}
let lang = window.hasOwnProperty('localStorage') || 'en';
setLang(lang);
const langArr = {
h1: {
en: 'Text',
ru: 'Teкст',
},
btn: {
en: 'Learn more',
ru: 'Узнать больше',
},
};
Answer the question
In order to leave comments, you need to log in
Found this solution:
html
<body>
<div class="lang df">
<button value="en" class="active" id="lang-en">EN</button>
<button value="ru" id="lang-ru">RU</button>
</div>
<div class="title">
<h1 class="lng-h1">Text</h1>
<button class="btn lng-btn">Learn more</button>
</div>
<script src="app.js"></script>
</body>
const langArr = {
h1: {
en: 'Text',
ru: 'Teкст',
},
btn: {
en: 'Learn more',
ru: 'Узнать больше',
},
};
document
.querySelectorAll('.lang button')
.forEach((b) => b.addEventListener('click', setLang));
function setLang() {
for (let key in langArr) {
let elem = document.querySelector('.lng-' + key);
if (elem) {
elem.innerHTML = langArr[key][this.value];
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question