Skip to content

Instantly share code, notes, and snippets.

@cisoun
Created April 9, 2024 06:39
Show Gist options
  • Save cisoun/225b8666f16bec90a5e0b1f9b260f033 to your computer and use it in GitHub Desktop.
Save cisoun/225b8666f16bec90a5e0b1f9b260f033 to your computer and use it in GitHub Desktop.
Localization in JS, the cheap way

Localization in JS

The Cheap way.

Summary

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.

JavaScript

// 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];
	}
}

HTML

<!-- 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment