Lightweight Language Switch In Vanilla JavaScript – i18NSwitch

Category: Javascript , Text | April 8, 2022
Author:LeonardoPinheiroLacerda
Views Total:360 views
Official Page:Go to website
Last Update:April 8, 2022
License:MIT

Preview:

Lightweight Language Switch In Vanilla JavaScript – i18NSwitch

Description:

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(
      "i18n-switch",
      {
        flag: CountryFlags.UNITED_STATES,
        language: english
      },
      {
        flag: CountryFlags.SPAIN,
        language: spain
      },
      general
);

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         = "https://unpkg.com/[email protected]/assets/brazil.png";
  static CHINA          = "https://unpkg.com/[email protected]/assets/china.png";
  static FRANCE         = "https://unpkg.com/[email protected]/assets/france.png";
  static GERMANY        = "https://unpkg.com/[email protected]/assets/germany.png";
  static INDIA          = "https://unpkg.com/[email protected]/assets/india.png";
  static ITALY          = "https://unpkg.com/[email protected]/assets/italy.png";
  static JAPAN          = "https://unpkg.com/[email protected]/assets/japan.png";
  static PORTUGAL       = "https://unpkg.com/[email protected]/assets/portugal.png";
  static RUSSIA         = "https://unpkg.com/[email protected]/assets/russia.png";
  static SPAIN          = "https://unpkg.com/[email protected]/assets/spain.png";
  static UNITED_KINGDOM = "https://unpkg.com/[email protected]/assets/united-kingdom.png";
  static UNITED_STATES  = "https://unpkg.com/[email protected]/assets/united-states.png";
}

7. Event handlers.

langSwitch.onChange(() => {
  if(langSwitch.isMainLanguageOn()){
    console.log("main");
  }else if(langSwitch.isSecondaryLanguageOn()){
    console.log("secondary");
  }
});

You Might Be Interested In:


Leave a Reply