Vanilla JavaScript Projects

Project 88, Content and data

Language Switcher

Make one page speak five languages. Text, plurals, dates, prices and even the page direction change together, and the choice is remembered.

Holaস্বাগতمرحبا
Main API
Intl.PluralRules
Layout
dir="rtl"
Dependencies
None
Your browser
Checking

Switch the language

Pick a language. Watch the text, direction, date, price and plural words change. Use the stepper to see plural rules in action.

1
See the translation file for this language

How it works

  1. Text lives in one object per languageEvery piece of text has a key like hero.title. Elements say which key they need with data-i18n, and one loop fills them in.
  2. Direction and language tagsSwitching to Arabic sets dir="rtl" and lang="ar", so the layout mirrors and screen readers use the right voice.
  3. Let Intl do the grammarIntl.PluralRules picks one, two, few, many or other for each language. Dates, numbers and prices use the matching locale.
const t = translations[lang];
document.querySelectorAll("[data-i18n]").forEach((el) => {
  el.textContent = el.dataset.i18n.split(".").reduce((o, k) => o[k], t);
});
document.documentElement.lang = lang;
document.documentElement.dir = lang === "ar" ? "rtl" : "ltr";

const rule = new Intl.PluralRules("ar").select(3);   // "few"
const text = t.cart[rule].replace("{n}", 3);