The Cheap way.
Here, we'll rely on a "lang" parameter in the URL (E.g: "?lang=fr") to know which language to use.
The code will then look for HTML elements with a data-i18n
attribute. This attribute contains
the key of the translation whose value will be set as the inner HTML of the element.
// main.js
const i18n = {
en: {
'title': 'Hello world!'
},
fr: {
'title': 'Salut le monde !'
}
};
const elements = document.querySelectorAll('[data-i18n]');
const query = window.location.search;
const params = new URLSearchParams(query);
const lang = params.get('lang');
if (lang && lang in i18n) {
for (const element of elements) {
element.innerHTML = i18n[lang][element.dataset.i18n];
}
}
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<script src="main.js" defer></script>
</head>
<body>
<h1 data-i18n="title">Fallback title</h1>
</body>
</body>
</html>
Now just open your HTML page and append "?lang=[code]" to the URL to change the language.