DEV Community

Walter Nascimento
Walter Nascimento

Posted on

Internationalize the paragraphs with JS

Using JavaScript, let's create this project

Code

HTML

<button id="changeEnEl">Inglรชs</button>
<button id="changePtBrEl">Portuguรชs</button>

<p data-i18n="title"></p>
<p data-i18n="name"></p>
<p data-i18n="password"></p>
Enter fullscreen mode Exit fullscreen mode

This code snippet is using a technique called "Internationalization and Localization" (i18n and L10n respectively) to change the language of the text displayed in the three

elements. The two buttons will be used to switch between languages. The "data-i18n" attribute on

elements is used to identify the specific text that needs to be translated. When the "changeEnEl" button is clicked, the text in

elements with the "data-i18n" attribute is replaced with the corresponding English translation. Likewise, when the "alterarPtBrEl" button is clicked, the text is replaced by the corresponding translation in Portuguese.

JS

'use strict';

const en = {
  title: 'Title',
  name: 'Name',
  password: 'Password',
};

const ptBr = {
  title: 'Titulo',
  name: 'Nome',
  password: 'Senha',
};

const elements = document.querySelectorAll('[data-i18n]');

let i18n = [];

function replaceText(el) {
  const key = el.dataset.i18n;
  el.innerText = i18n[key] || key;
}

function changeLang(lang) {
  i18n = eval(lang);
  elements.forEach((el) => replaceText(el));
}

changeEnEl.addEventListener('click', () => changeLang('en'));
changePtBrEl.addEventListener('click', () => changeLang('ptBr'));
Enter fullscreen mode Exit fullscreen mode

It uses the data-i18n attribute to identify elements in the HTML that need to be translated. It then selects all the elements with that attribute using document.querySelectorAll('[data-i18n]').

The function replaceText(el) takes an element as a parameter, and it replaces the inner text of the element with the translation from the i18n object. If the translation is not found, the key is used as a fallback.

The function changeLang(lang) takes a language code as a parameter, it sets the i18n object to the desired language, and calls replaceText(el) for each element with the data-i18n attribute.

The last two lines of code are adding click event listeners to the changeEnEl and changePtBrEl elements respectively. When clicked on it, it will call the changeLang function with the appropriate language code.

Demo

See below for the complete working project.

if you can't see it click here and see the final result


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

๐Ÿ˜Š๐Ÿ˜Š See you later! ๐Ÿ˜Š๐Ÿ˜Š


Support Me

Youtube - WalterNascimentoBarroso
Github - WalterNascimentoBarroso
Codepen - WalterNascimentoBarroso

Top comments (0)