Search code examples
htmlweblocalizationmultilingual

Simplest way to create multiple-language one-page website


There are plenty of questions likes this, but I've read many of them and what I saw appears to be too complex for my very simplistic case.

I have a super simple one-page website (picstalk.app in case you care). It is nothing more than a few divs with text. I'm looking for the simplest way possible to have that in multiple languages, so that the text with the browser's default language is shown automatically and of course there is a way to switch languages manually.

Ideas?

Thanks.


Solution

  • I'm not sure if this is efficient but since you have very little text, This will work.

    // Maintain a supported Language List
    var langList = ['en', 'zh'];
    // Get browser Language
    var userLang = navigator.language || navigator.userLanguage;
    // extract Language (en-US => en)
    userLang = userLang.substring(0, 2);
    // Call the function to set language
    changeLang(userLang);
    
    // function to change language
    function changeLang(lang) {
      langList.forEach((langEle) => {
        // if language matches, display
        if (langEle == lang) {
          var langElems = document.querySelectorAll('.' + langEle)
          langElems.forEach((elem) => {
            elem.style.display = "block"
          })
        }
        // hide the language text
        else {
          hideLang(langEle)
        }
      })
    }
    
    // function to hide language
    function hideLang(lang) {
      var langElems = document.querySelectorAll('.' + lang)
      langElems.forEach((elem) => {
        elem.style.display = "none"
      })
    }
    <h1><span lang="en" class="en">Hello</span> <span lang="zh" class="zh">你好</span></h1>
    <button onclick="changeLang('en')">English</button><button onclick="changeLang('zh')">Chinese</button>