Lightweight Language Switch In Vanilla JavaScript – i18NSwitch

Category: Javascript , Text | April 8, 2022
Views Total:1,213 views
Official Page:Go to website
Last Update:April 8, 2022


Lightweight Language Switch In Vanilla JavaScript – i18NSwitch


If you’re looking to create a website that supports multiple languages, using a JavaScript library like i18NSwitch can be an easy way to make sure your content is accessible to a wider audience.

i18NSwitch is an easy-to-use library that makes it simple to toggle between supported languages on your website.

It’s lightweight and can be used on any site without slowing down loading times or impacting the performance of your application.

How to use it:

1. Import the i18NSwitch’s JavaScript and Stylesheet.

<link rel="stylesheet" href="style/I18NSwitch.css" />
<script src="script/I18NSwitch.js"></script>

2. Create an empty element to hold the language switch.

<div id="i18n-switch"></div>

3. Create translations for each language.

const english = {};
const spain = {
  "hello": "¡Hola Mundo!"
const general = {
  "hello": "Hello world!"

4. Initialize the i18NSwitch, define the languages, and specify the flag icon for each language.

const langSwitch = new I18NSwitch(
        flag: CountryFlags.UNITED_STATES,
        language: english
        flag: CountryFlags.SPAIN,
        language: spain

5. Add the data-i18n attribute to the target content which should be translated.

<p data-i18n="hello"></p>

6. Add more country flags as follows:

class CountryFlags {
  static BRAZIL         = "[email protected]/assets/brazil.png";
  static CHINA          = "[email protected]/assets/china.png";
  static FRANCE         = "[email protected]/assets/france.png";
  static GERMANY        = "[email protected]/assets/germany.png";
  static INDIA          = "[email protected]/assets/india.png";
  static ITALY          = "[email protected]/assets/italy.png";
  static JAPAN          = "[email protected]/assets/japan.png";
  static PORTUGAL       = "[email protected]/assets/portugal.png";
  static RUSSIA         = "[email protected]/assets/russia.png";
  static SPAIN          = "[email protected]/assets/spain.png";
  static UNITED_KINGDOM = "[email protected]/assets/united-kingdom.png";
  static UNITED_STATES  = "[email protected]/assets/united-states.png";

7. Event handlers.

langSwitch.onChange(() => {
  }else if(langSwitch.isSecondaryLanguageOn()){

You Might Be Interested In:

Leave a Reply