D
D
Denis_81062021-06-08 21:23:32
JavaScript
Denis_8106, 2021-06-08 21:23:32

How to make a multilingual site in pure JS?

There is such an unpretentious code for the multilingual site.
html

<body>
  <div class="lang df">
    <a href="#en" id="lang-en">EN</a>
    <a href="#ru" id="lang-ru">RU</a>
  </div>

  <div class="title">
    <h1 class="lng-h1">Text</h1>
    <button class="btn lng-btn">
      Learn more
    </button>
  </div>

  <script src="app.js"></script>
</body>

css
.df {
  display: flex;
  justify-content: space-between;
  width: 60px;
}

js
const langArr = {
  en: {
    h1: 'Text',
    btn: 'Learn more',
  },

  ru: {
    h1: 'Teкст',
    btn: 'Узнать больше',
  },
};

const langEn = document.querySelector('#lang-en');
const langRu = document.querySelector('#lang-ru');

langEn.addEventListener('click', setLang.bind(null, 'en'));
langRu.addEventListener('click', setLang.bind(null, 'ru'));

function setLang(lang) {
  if (!langArr.hasOwnProperty(lang)) return;
  if (window.hasOwnProperty('localStorage'))
    window.localStorage.setItem('lang', lang);
  for (let key in langArr[lang]) {
    let elem = document.querySelector('.lng-' + key);
    if (elem) {
      elem.innerHTML = langArr[lang][key];
    }
  }
}
let lang = window.hasOwnProperty('localStorage') || 'en';
setLang(lang);


Now a simple question - How to remake the JS code with a different const langArr layout?

const langArr = {
  h1: {
    en: 'Text',
    ru: 'Teкст',
  },

  btn: {
    en: 'Learn more',
    ru: 'Узнать больше',
  },
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis_8106, 2021-06-09
@Denis_8106

Found this solution:
html

<body>
  <div class="lang df">
    <button value="en" class="active" id="lang-en">EN</button>
    <button value="ru" id="lang-ru">RU</button>
  </div>

  <div class="title">
    <h1 class="lng-h1">Text</h1>
    <button class="btn lng-btn">Learn more</button>
  </div>

  <script src="app.js"></script>
</body>

js
const langArr = {
  h1: {
    en: 'Text',
    ru: 'Teкст',
  },

  btn: {
    en: 'Learn more',
    ru: 'Узнать больше',
  },
};

document
  .querySelectorAll('.lang button')
  .forEach((b) => b.addEventListener('click', setLang));

function setLang() {
  for (let key in langArr) {
    let elem = document.querySelector('.lng-' + key);
    if (elem) {
      elem.innerHTML = langArr[key][this.value];
    }
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question